Displaying php curl Json Array Data in Javascript

884

I am trying to Displaying PHP curl json array data in javascript.

if I echo

// curl output

$response = curl_exec($curl);
echo $response; 

I will be having this data in the format below as my output

{"items":[{"id":"1","food":"rice","Amount":"100","condition":"paid"},
{"id":"2","food":"beans","Amount":"200","condition":"paid"},
{"id":"3","food":"yam","Amount":"50","condition":"not paid"},
{"id":"4","food":"tomatoes","Amount":"100","condition":"paid"},
{"id":"5","food":"potato","Amount":"700","condition":"paid"}]}

Question is how can I display the data in Javascript?

I have tried the code below but am having error "Undefine".

Can someone help me out?

Below is the code of my output in Javascript.

    function loadData(){
$.post('json.php',
function(response){

    $.each(JSON.parse(response),

function(i,v){  


$('.info').append('<li><div class="msg-lhs"><span>'+v.id+'</span> <span>'+v.food+'</span> <span>'+v.Amount+'</span> <span>'+v.condition+'</span></div></li>');

});

$('.info').animate({scrollTop: $('.info').prop("scrollHeight")}, 500);

});
714

Answer

Solution:

I don't know what is really messed up with your code, but I came up with a slightly different approach that works fine.

Note: assuming that you're getting data from yourcurl request fine. just parsed your result outside the loop iteration and usingforEach loop.

var response = '{"items":
     [{"id":"1","food":"rice","Amount":"100","condition":"paid"},\
      {"id":"2","food":"beans","Amount":"200","condition":"paid"},\
      {"id":"3","food":"yam","Amount":"50","condition":"not paid"},\

      {"id":"4","food":"tomatoes","Amount":"100","condition":"paid"},\
      {"id":"5","food":"potato","Amount":"700","condition":"paid"}]}';
var parsed = JSON.parse(response)
parsed.items.forEach(function(v) {
$('.info').append('<li><div class="msg-lhs"><span>'+v.id+'</span>    
    <span>'+v.food+'</span> <span>'+v.Amount+'</span> 
    <span>'+v.condition+'</span></div></li>');
});
$('.info').animate({scrollTop: $('.info').prop("scrollHeight")}, 500);

Here is fiddle

People are also looking for solutions to the problem: php - Youtube [Data-API] LiveChat where logged-in user is moderator

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.