Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a 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?

share|improve this question

5 Answers 5

up vote 91 down vote accepted

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
        }));
    });
});
share|improve this answer
    
success. thanks. DO i have to send json pr i can send anything from my php function? –  Patrioticcow Jan 21 '12 at 9:14
3  
@Patrioticcow, you can send JSON as well. In this case you will need to set the contentType: 'application/json' setting in your $.ajax function and JSON serialize the data parameter, like that: data: JSON.stringify({ get_param: 'value' }). Then in your php script you would need to json decode to get back the original object. –  Darin Dimitrov Jan 21 '12 at 9:16
    
Old thread, but I just wanted to thank @Darin Dimitrov for the parsing of a returned json object. It was VERY helpful. Thanks! Thanks! Thanks! –  TimSPQR Oct 17 '13 at 23:53
    
What is this "done: function"? Is that the same as "success"? I don't see it in the docs. –  Buttle Butkus Sep 30 '14 at 22:34
1  
@ButtleButkus that was a bad edit. I did a rollback to the original post –  dave Feb 5 at 20:13

setting dataType:'json' will parse json for you

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

or else you can use parseJSON

var parsedJson = $.parseJSON(jsonToBeParsed);

here is how you can iterate

var j ='[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]';

iterate using each

var json = $.parseJSON(j);
$(json).each(function(i,val){
    $.each(val,function(k,v){
          console.log(k+" : "+ v);     
});
});

http://jsfiddle.net/fyxZt/4/

share|improve this answer
    
success. thanks. –  Patrioticcow Jan 21 '12 at 9:14
    
nice work @3nigma –  Md. Shariful Islam Jun 18 '13 at 21:45
    
tnx pal ....... –  3nigma Jun 19 '13 at 17:36
    
This helped me a lot. –  Human Being Jul 11 '13 at 15:48
    
Simple, Elegant. –  BilliAm Mar 11 at 21:00

Use that code.

     $.ajax({

            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Your URL",
            data: "{}",
            dataType: "json",
            success: function (data) {
                alert(data);
            },
            error: function (result) {
                alert("Error");
            }
        });
share|improve this answer
 $(document).ready(function () {
    $.ajax({ 
        type: 'GET', 
        url: '/functions.php', 
        data: { get_param: 'value' }, 
        success: function (data) { 
         for (var i=0;i<data.length;++i)
         {
         $('#cand').append('<div class="name">data[i].name</>');
         }
        }
    });
});
share|improve this answer
var jsonP = "person" : [ { "id" : "1", "name" : "test1" },
  { "id" : "2", "name" : "test2" },
  { "id" : "3", "name" : "test3" },
  { "id" : "4", "name" : "test4" },
  { "id" : "5", "name" : "test5" } ];

var cand = document.getElementById("cand");
var json_arr = [];
$.each(jsonP.person,function(key,value){
    json_arr.push(key+' . '+value.name  + '<br>');
    cand.innerHTML = json_arr;
});

<div id="cand">
</div>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.