Pedroson
Pedroson

Reputation: 109

How to use $.each with ajax to get JSON?

I am using ajax to get JSON from an API, however I am having a problem, retrieving the data. The code for ajax function is fine as I am using it elsewhere. I believe that the issue is with the .done(function().

        $.ajax({
            url: "http://127.0.0.1:4001/Barratt/getData.php",
            //dataType: 'json',
            //method: 'GET',
            //contentType: 'application/json'
            data: {url: developmentURL},
            method: 'POST'
        })
        .done(function(data) {
            //var developments = [];
            $.each(data, function() {
                $.each(this, function(i, obj) {
                    console.log(i, obj.Name + ' = ' + obj.ItemKey);
                    //developments.push();
                });
            });
        })
        .fail(function() {
            alert('Failed to fetch data')
        });

This is the code I am using, which just logs loads of 0 "undefined=undefined". However I have the .done(function() working in a jsfiddle, with the JSON hard coded. So I'm not sure where the problem lies.

Here is the fiddle

Upvotes: 0

Views: 139

Answers (3)

MrAlex6204
MrAlex6204

Reputation: 167

I assume the data that you retrive is an array of Json according to your code. You forgot add key and value in the $.each callback function to loop into each Json value.

$.ajax({
            url: "http://127.0.0.1:4001/Barratt/getData.php",
            //dataType: 'json',
            //method: 'GET',
            //contentType: 'application/json'
            data: {url: developmentURL},
            method: 'POST'
        })
        .done(function(data) {
            //var developments = [];
            $.each(data, function(key,value) {
                $.each(value, function(subKey, subValue) {
                    console.log(subKey, subValue.Name + ' = ' + subValue.ItemKey);
                    //developments.push();
                });
            });
        })
        .fail(function() {
            alert('Failed to fetch data')
        });

Upvotes: 0

taxicala
taxicala

Reputation: 21759

If you want to avoid using JSON.parse you can Set the dataType to just 'json' and you will automatically recieve a parsed json response:

    $.ajax({
        url: "http://127.0.0.1:4001/Barratt/getData.php",
        dataType: 'json', //Uncomment this line
        //method: 'GET',
        //contentType: 'application/json'
        data: {
            url: developmentURL
        },
        method: 'POST'
    })

Or you can also make use of jquery $.getJSON api.

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

The data is of string type. Parse the string into JSON before looping:

data = JSON.parse(data);
$.each(data, function() {

Upvotes: 4

Related Questions