1

i am outputting json data from a php file (example of my output)

{"news":[{"title":"title news example1","content":"blabla bla 1","img":"url"},
{"title":"title news example2","content":"blabla bla 2","img":"url2"},
{"title":"title news example3","content":"blabla bla 3","img":"url3"},
{"title":"title news example4","content":"blabla bla 4","img":"url4"}]}

how can i show all these data to div #news using jquery getjson or get and using each?

2 Answers 2

2

This will use jQuery's append() method to add an h2 and p tag for each article to the #news div. Obviously, you can customize the $.each callback as you need.

Update the reason for your undefined errors was because the callback for the each() method was missing the index of the array as the first parameter. I updated my example appropriately.

<script type="text/javascript">
  jQuery(function($){
    $.getJSON('uri/to/file.php', function(data) {
      $.each(data['news'], function(i, article){
        $('#news').append('<h2>' + article['title'] + '</h2><p>' + article['content'] + '</p>');
      });
    });
  });
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

I get 6 rows of h2 undefined and 6 rows of p undefined :/
Looks like I forgot the first parameter for the each() callback. I updated the example accordingly :)
0

I solved it this way, by puttin the content of title and content in a new var, i dont know why the fist way was not working, but this way work perfectly :)

Query(function($){
    $.getJSON('file.php', function(data) {
        $.each(data['news'], function(i,row){
        var titulli = row.title;
        var contenti = row.content;
    $('#news').append('<h2>' + title + '</h2><p>' + content + '</p>');


      });
    });
  });   

Comments

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.