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);
});
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 your curl
request fine. just parsed your result outside the loop iteration and using forEach
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.