Display all data using JSONP

I've encountered an issue with JSONP. Although I was able to successfully load my JSONP data into my html file, I am struggling to display all the information. I have attempted using both a for loop and $.each method without any luck.

Here is the JSONP in the php file:

<?php echo $_GET["callback"] ?> (
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"indexpit.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"indexso.html"
}
);

Below is the script used to call the JSONP:

<script type="text/javascript">
$.ajax({
type: 'GET',
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
url: 'http://mllsdemode.be/Ex-cache/home.php',
success: function(json) {
            for (var key in json) {
                var el = document.getElementById("home");
                el.innerHTML = "<li><a href=" + json.link + " data-ajax='false'><img src=" + json.img + "><div class='dsc'>" + json.expo + "<br><em>" + json.datum + "</em></div></a></li>";
            }
         },
error: function() { alert("Error reading JSONP file"); }
});
</script>

Does anyone have a solution on how to display all the information? Currently, only the data for pit is showing up, not for Space Odessy 2.0.

Answer №1

The JSONP should look like this:

<?php echo $_GET["callback"] ?> (
    [
        {
        "expo":"pit",
        "datum":"05.06.2011 - 05.06.2016",
        "img":"images/pit_home.jpg",
        "link":"indexpit.html"
        },
        {
        "expo":"Space Odyssey 2.0",
        "datum":"17.02 - 19.05.2013",
        "img":"images/so_home.jpg",
        "link":"indexso.html"
        }
    ]
);

The error was in the missing [] brackets around the array, causing two arguments to be passed instead of one array.

Additionally, there was a mistake in the loop logic. It should iterate over an array, not a single object, and append HTML elements instead of replacing them.

success: function(json) {
    var $home = $("#home");
    $home.empty();
    $.each(json, function(i, el) {
        $home.append("<li><a href=" + el.link + " data-ajax='false'><img src=" + el.img + "><div class='dsc'>" + el.expo + "<br><em>" + el.datum + "</em></div></a></li>");
    });
}

Answer №2

<?php echo $_GET["callback"] ?> ([
{
    "event":"Pit Exhibition",
    "date":"05.06.2011 - 05.06.2016",
    "image":"images/pit_home.jpg",
    "link":"indexpit.html"
},
{
    "event":"Space Odyssey 2.0",
    "date":"17.02 - 19.05.2013",
    "image":"images/so_home.jpg",
    "link":"indexso.html"
}]);

.

$(json).each(function (index, item) {
    var container = document.getElementById("home");
    container.innerHTML += ("<li><a href=" + item.link + " data-ajax='false'><img src=" + item.image + "><div class='description'>" + item.event + "<br><em>" + item.date + "</em></div></a></li>");
});

Answer №3

Give this a shot.

let data = JSON.parse(data);

You can now iterate through it like so :

for(let i=0; i<data.length; i++)
{
   console.log(data[i].expo);
}

Make sure your array is in the format of [{},{}];

Appreciate it!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Variables in an Angular application are not appearing in the HTML rendering

Currently learning AngularJS as I develop a web application. After going through tutorials, I started with a basic list but am baffled as to why my browser only shows {{title}}. In my app.js module, here's the snippet where I defined the controller: ...

Using regular expressions in JavaScript, eliminate all characters preceding a specified final character

I am attempting to eliminate all text that precedes the last character in a Regex pattern. For example: rom.com/run/login.php Would turn into: login.php Can someone guide me on how to achieve this using JavaScript? I have limited experience with regul ...

"Effortlessly handle adding and removing items with a single button using

I am working on creating a button functionality where clicking it will either add or delete a record from the database. This button serves as a 'favorite' feature. The desired behavior is as follows; Upon clicking the 'fav' button, th ...

Working with AngularJS $resource: including an array element in paramDefaults

I'm currently working with the twitch.tv API and utilizing the Angular $resource factory. My goal is to access the endpoint: GET /channels/:channel. What I want to achieve is to retrieve the channel for each element within an array. I attempted using ...

Troubleshooting Challenges with JavaScript DOM Manipulation

I am facing an issue with a table where I need the first column to remain fixed when scrolling horizontally. The code snippet below works perfectly for the first column of td's, but fails to work for the tr's. Despite checking the code thoroughly ...

Problem Alert: Click Event Not Functioning on Generated Links

Take a look at these two code snippets. Despite other jQuery functions in the same JS file working fine on the UL element, nothing seems to be happening with these. Is there something obvious that I am missing? <ul id="activityPaganation" class="paga ...

Setting up the karma ng-html2js preprocessor to locate my templates within a specific folder

Currently, I am facing an issue where I need to set the templateUrl: "partials/my-directive.html" However, I find that I have to use templateUrl: "app/partials/my-directive.html for it to be loaded by Karma. This is how my folder structure looks like (fo ...

What is the best way to tally the occurrences or total of identical words in PHP?

I am having trouble counting these words, Here is the data I have: web = 1 sistem=1 web=1 sistem=1 web=1 sistem=1 sistem=0 sistem=0 web=0 sistem=0 web=0 sistem=0 web=0 web=0 I would like to see the result as follows : web = 3 sistem = 3 I tried using arr ...

Showing information from JSON in a pie chart utilizing chart.js

Recently, I started using chart.js for the first time and encountered a minor issue that has me stumped. My code is only displaying the labels without rendering the pie chart itself. I've been referencing examples from the chart.js documentation avai ...

Error TS2322: Cannot assign type 'Promise<Hero | undefined>' to type 'Promise<Hero>'

I am currently studying angular4 using the angular tutorial. Here is a function to retrieve a hero from a service: @Injectable() export class HeroService { getHeroes(): Promise<Hero[]> { return new Promise(resolve => { // ...

The react-native-video-controls package was used in React Native. When the onBack event was triggered, it successfully navigated back to the initial screen. However, upon returning

https://i.stack.imgur.com/GsS3d.png https://i.stack.imgur.com/HYBOU.png Attached are screenshots showing the issue I am experiencing with my video player. When I click the back button, the screen does not return to its initial state and the flatlist items ...

Arranging an array based on relationships between children and parents

I have an array of objects like this: const data = [{id: 3, name: ''}, {id: 4, name: ''}, {id: 5, name: '', parent: 3}, {id: 6, name: '', parent: 5}, {id: 7, name: '', parent: 4}, {id: 8, name: '&ap ...

Dealing with multipart/form-data in Express using cloud functions in the upcoming year of 2022

Seeking advice on handling multipart/form-data requests in an Express backend with Google Cloud Functions in 2022. Despite numerous attempts, the issue remains unresolved after extensive research and testing various methods that work locally but fail when ...

Tips for adding a string variable to a JQuery HTML element attribute

Hi there, I've been working on a JQuery code to append data to a div element and it's been successful so far. Here is the code: $('#conversation').append('<div id="receiver"><p><b>' + username + ':< ...

Creating a Form with Dynamic HTML when Button is Clicked

I have been working on enhancing the functionality of my website app located at , but unfortunately, I have not been successful so far. My goal is to introduce a vendor information form with just one click of a button and then enable users to add products ...

Removing an item from a JSON array based on its value using jQuery

This is a section of my JSON array: var videos = $j.parseJSON(' [ { "privacy":"public", "id":"1169341693" }, { "privacy":"private", "id":"803641223" }, { "privacy":"public", "id":"1300612600" }, ...... When I use co ...

Is it a wise decision to provide the client with a new token just one minute before the expiration of the old one?

When monitoring my backend, I constantly check the remaining time before the JWT expires, which is set to 15 minutes. If there is only one minute left or less, I generate a new JWT and include it in the response header as a setToken. The front-end can then ...

Creating an uncomplicated selector bar for a basic javascript slideshow

I've spent the last couple of hours teaching myself some basic JavaScript, so please bear with me. Currently, I have a simple code in place for a straightforward slideshow on a website. Here is the JavaScript I'm using (where the 'slide&apo ...

What causes the form to be submitted when the text input is changed?

I'm puzzled by the behavior of this code snippet that triggers form submission when the input value changes: <form> <input type="text" onchange="submit();"> </form> Typically, I would expect something along t ...

Using JavaScript and Codigniter to populate a drop down box with an array

One of the key elements in my Codeigniter project is the $location variable, which is set using sessions and can represent cities like 'Austin', 'Houston', and so on. Each location has its own unique tours to offer. Instead of manually ...