1

I can't seem to get this working, i am retrieving some json data, and just trying to loop through it an append it to a DIV. here is my code:

HOW THE JSON IS RETURNED (PHP)

{"list":[{"subscribe":"example"},{"subscribe":"example2"},{"subscribe":"example3"},{"subscribe":"example4"},{"subscribe":"example5"}]}

MY JSON CALL USING JQUERY

$.getJSON("article.php",function(data)
   $.each(data.list, function(i,data) {
      var listData = "<li>" + data.subscribe + "</li>";
      $('#lists').append(listData);
   });
});

I am not retrieving any errors in the console, but nothing is happening, i know the call is successful, am i doing the .each loop correctly? can anyone please help?

1
  • Have you tried sticking a console.log before your iterative loop to see what data is returned? Commented May 12, 2011 at 5:39

3 Answers 3

5

Maybe you can try this:

$.each(data.list, function(i, item) {
    var listData = "<li>" + item.subscribe + "</li>";
    $('#lists').append(listData);
});

Just change function(i, data) to function(i, item).

By reusing the variable name data in the way that you are, you are not actually looping through the array as you expect to.

Sign up to request clarification or add additional context in comments.

Comments

2

I personally haven't used $.each to loop through an array because I always just do a for loop, so you can try this:

$.getJSON("article.php", function (d) {
    var listsDiv = $("#lists");

    for (var i = 0; i < d.list.length; i++) {
        listsDiv.append("<li>" + d.list[i].subscribe + "</li>");
    };
});

I'm 99% confident that it should work for what you need. Also, it's better to have a variable to your div outside of the loop and append in the loop because right now your code is traversing the DOM for that div for each object in your JSON list.

Also, I'm not sure if you're truncating the JSON response, but you may want to attach a 'success' property and check for that. So you're code would be upgraded to this:

$.getJSON("article.php", function (d) {
    if (d.success) {
        var listsDiv = $("#lists");

        for (var i = 0; i < d.list.length; i++) {
            listsDiv.append("<li>" + d.list[i].subscribe + "</li>");
        };
    } else {
        // Do something else to notify the user that the data could not be retrieved.
    };
});

Comments

1

Seems you got a syntax error. A { is missing after first line i.e the starting { for "function(data)" in first line

1 Comment

+1 Or it's a bad copy/paste, but never the less it's missing. Good job finding that, I looked right passed it, lol...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.