Search code examples
javascriptjqueryjsonajaxparsing

How to parse JSON data with jQuery / JavaScript?


I have an AJAX call that returns some JSON like this:

$(document).ready(function () {
    $.ajax({ 
        type: 'GET', 
        url: 'http://example/functions.php', 
        data: { get_param: 'value' }, 
        success: function (data) { 
            var names = data
            $('#cand').html(data);
        }
    });
});

Inside the #cand div I'll get:

[ { "id" : "1", "name" : "test1" },
  { "id" : "2", "name" : "test2" },
  { "id" : "3", "name" : "test3" },
  { "id" : "4", "name" : "test4" },
  { "id" : "5", "name" : "test5" } ]

How can I loop through this data and place each name in a div?


Solution

  • Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json' parameter.

    Then you could use the $.each() function to loop through the data:

    $.ajax({ 
        type: 'GET', 
        url: 'http://example/functions.php', 
        data: { get_param: 'value' }, 
        dataType: 'json',
        success: function (data) { 
            $.each(data, function(index, element) {
                $('body').append($('<div>', {
                    text: element.name
                }));
            });
        }
    });
    

    or use the $.getJSON method:

    $.getJSON('/functions.php', { get_param: 'value' }, function(data) {
        $.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });
    });