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

Exploration of frontend utilization of web API resources

I've come across this issue multiple times. Whenever I modify a resource's result or parameters and search for where it's utilized, I always end up overlooking some hidden part of the application. Do you have any effective techniques to loc ...

Is there a way to display various data with an onClick event without overwriting the existing render?

In the process of developing a text-based RPG using React/Context API/UseReducer, I wanted to hone my skills with useState in order to showcase objects from an onclick event. So far, I've succeeded in displaying an object from an array based on button ...

Trigger the ontextchanged() event for an asp:TextBox using Javascript

I have a specific asp:TextBox that is structured in the following way: <asp:TextBox runat="server" AutoPostBack="True" ID="txtG1" ontextchanged="txtG1_TextChanged" onmouseout="javascript:RefreshIt(this)"/> In addition to this, there is a Javascript ...

Retrieve the item within the nested array that is contained within the outer object

I have a collection of objects, each containing nested arrays. My goal is to access the specific object inside one of those arrays. How can I achieve this? For instance, take a look at my function below where I currently log each array to the console. Wha ...

Issues with retrieving JSON data from Google Books API object

I've been working on retrieving data from the Google Books API and displaying the titles of the first 10 results on a web page. The site is successfully making the request, and I have a callback function that handles the results as shown below: funct ...

JavaScript Fullcalendar script - converting the names of months and days

I recently integrated the Fullcalendar script into my website (https://fullcalendar.io/). Most of the features are functioning correctly, however, I am seeking to translate the English names of months and days of the week. Within the downloaded package, ...

Angular JS is facing difficulties in being able to call upon another directive

I'm encountering an issue where including another directive related to the current one results in the following error message Error: [$compile:ctreq] http://errors.angularjs.org/1.2.10/$compile/ctreq?p0=myApp.pagereel&p1=ngTransclude Script.js ...

Failed to build development environment: Unable to assign the attribute 'fileSystem' to a null value

I'm attempting to launch an Ionic 2 Application, but I keep encountering this error when running ionic serve Error - build dev failed: Unable to assign a value to the 'fileSystem' property of object null Here is the complete log: λ ion ...

Having trouble utilizing Reactjs Pagination to navigate through the data

I'm currently working on implementing pagination for a list of 50 records, but I'm encountering an issue. Even though I have the code below, it only displays 10 records and I'm unaware of how to show the next set of 10 records until all 50 a ...

What is the best method to determine the mean score by utilizing the ID values obtained from API responses?

These are the responses retrieved from the API: const attractions = [ {"id": 1,"name": "drive on avenue"}, {"id": 2, "name": "diving"}, {"id": 3,"name": "visiting ma ...

Issue with React Google Maps Api: Error occurs while trying to access undefined properties for reading 'emit'

I'm trying to integrate a map using the google-map-react API, but I keep encountering the following error: google_map.js:428 Uncaught TypeError: Cannot read properties of undefined (reading 'emit') at o.r.componentDidUpdate (google_map.js: ...

Update the JavaScript and CSS files following an AJAX request with $.get

I am encountering an issue where my global CSS and JS files contain all the necessary definitions, but when I load new HTML blocks via AJAX $.get, these new elements do not receive the correct CSS/JS definitions. Is there a convenient way to refresh the ...

Using Cheerio with a Node.js bot

I am currently utilizing Cheerio to extract information from web pages in my .js files. However, I would like these files to automatically restart every 1 day to check for any new data. Instead of using setTimeout, which may not be efficient for managing ...

Executing tasks in a While loop with NodeJS and attaching actions to a Promise

I am relatively new to incorporating Promises in NodeJS. My current task involves creating a promise dynamically with multiple actions based on the characters found in a string. //let actions = []; getPromise = get(srcBucket, srcKey); // Retrieve the imag ...

During operational hours, an Ajax request may cause interruptions to the website's functionality

Having an issue with a large ajax request: I am querying a PHP file that makes some cURL requests, taking 15-20 seconds to complete and then returning JSON on my webpage. It's a standard ajax request, but I found a strange bug. While the ajax query i ...

The base64 code generated by the toDataURL method on the canvas appears to be incorrect

I am facing an issue with my code while using canvas to draw a cropped image with base 64. The problem is that it works perfectly on Chrome but gives me a blank image on Firefox. async function base64SquareCrop(imgbase64, size = 224) { const img = docume ...

What is the best way to attach every sibling element to its adjacent sibling using jQuery?

I've been working with divs in Wordpress, where each div contains a ul element. <div class="list-item"> <div class="elimore_trim"> Lorem ipsum </div> <ul class="hyrra-forrad-size-list"> <li>Rent 1< ...

I am unable to get JQuery UI Dialog to open on my end

Coding in HTML: <button type="button" class="btn btn-success" style="margin-bottom:14px" id="btnAdd" onclick="modaladdedit('URLToMyController')"><i class="fa fa-plus"> Add New</i></button> HEAD Tag Setup: <link rel=" ...

Issues encountered while utilizing the jQuery function $.ajax()

I'm encountering issues with utilizing ajax in conjunction with jQuery... Here is the script I am using: $(document).ready(function() { $('rel[close]').click(function() { $(this.parent).close(); }); $('a[rel=trac ...

What is the mechanism behind range traversal in Javascript?

Exploring the createRange() function and related constructs in Javascript has sparked my curiosity about its practical applications. During my search, I stumbled upon an interesting application called "" that allows users to highlight text with mouse clic ...