Displaying php curl Json Array Data in Javascript - javascript

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

Related

Laravel Error returns when it does json_decode

I get the data in json format with the help of javascript. The javascript code I wrote actually sends the data in the format I want as follows:
var log_lists = JSON.stringify(Object.assign({}, $scope.log_list));
when I checked it on the internet, I checked that the incoming data is in json format and it was verified by all
When I send the requests, it is received correctly by the controller and when I return, I see the data returned in the console as follows.
My controller code
$log_example = $request->all();
return $log_example;
return data
{
"0":["1","SALES","5,00","REMOVED"],
"1":["2","SALES","10,00","REMOVED"],
"2":["1","BUYER","2","DROPPED"]
}
I use the json_decode function to run it in the foreach loop and when I return the data again I get the error "server error"
return json_decode($log_example, true);
// returns with errors
I couldn't find where I made a mistake.
Thank you for your help and suggestions.
$request->all() return an array by default.
First encode and then decode as below
$log_example = $request->all();
$logs = json_encode($log_example);
$data = json_decode((string) $logs, true);
return $data;

Return JSON object from php script

I am making an AJAX GET request using jQuery to a PHP file. I want the PHP script to return a JSON object, however, currently it is returning a JSON string. I realise I can use JSON.parse in the jQuery code, however, any experience I have in making an AJAX call to an API a JSON object is returned. I am trying to do the same with the php script however, it is returning a string as opposed to an object.
Does anyone know what the best practice is here, and if the best practise is to return a JSON object how I would do this using PHP?
Please see the code below:
js
$.get('test.php', function(data){
console.log((data));
});
php
<?php
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
In your PHP file, change the content type to application/json.
JS
$.get('/process.php', function(data) {
console.log(data);
} );
PHP
<?php
header( "Content-type: application/json" );
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
Then your console should read Object {test: "true"} rather than just the JSON string.
Add json to the end of your get function to return json
$.get('test.php', function(data){
console.log((data));
},'json');//here
and/or add this header in php
header('Content-Type: application/json');
more info here
Without modifying PHP script you can do:
$.get( "test.php", function( data ) {
var arr = $.parseJSON(data);
console.log(arr);
alert(arr.test);
});

Working with javascript array

Hi I have a php script that successfully gets an array of data from an exsternal xml source, the array is called $file, I know that the php array is populated by using print_r($file).
I have tried to use the following php to pass to a javascript session:
//Convert to JSON Array
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
But either this hasn't worked, or the following JS code below is wrong:
var jsonarray = result["json_array"];
alert(JSON.stringify(jsonarray));
Could someone please tell me where I am going wrong?
You should not use JSON.stringify there. JSON.parse is what you are looking for. Since you want to parse existing JSON, not create new JSON.
edit: Your code is a bit odd. I'd think you want something like this
php
//Convert to JSON Array
echo json_encode($file, JSON_FORCE_OBJECT);
js
alert(JSON.parse(data)); // Where data is the contents you've fetched from the server
You have to encapsulate php code :
<?php
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
?>
var jsonarray = <?= $result["json_array"] ?>;
alert(JSON.parse(jsonarray));

json from js to php - failed to open stream: http request failed

I am trying to send some json data from js to php, and pass it to mongo by REST.
The following outputs json string (that works fine later if I just put it as string in PHP file, please see snippet below).
JS to send json:
var s = JSON.stringify(send); //s contains previous data in arrays, etc
ic(s);
function ic(s){
var ajaxUrl = './iM.php';
$.getJSON(ajaxUrl,
{da: s},
function(data) {
console.log (data);
});
}
in iM.php:
$s = $_GET["da"]; // <-- doesn't work
//$s = '{"r":"pax","c":1,"w":["kiwi","melon"],"g":["cat","dog"]}'; //<-- works fine
$opts = array(
"http" => array(
"method" => "POST",
"header" => "Content-type: application/json",
"content" => $s,
),
);
$context = stream_context_create($opts);
$result = file_get_contents("https://api.mongolab.com/api/1/databases/$db/collections/$collection?apiKey=$key", false, $context);
var_dump($result); // Dumps the response document
At the firefox debugger, I can see the file is actually being called, however No data is added.
error_log file is created:
failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
I also tried urlencode($s) in php, still not working.
$db, $collection and $key are defiend in php, no problem there.
What am I missing?
Basically JSON.stringify(send) function is designed in such way that it will make your json into what you are getting.
JSON.stringify(value[, replacer[, space]])
You should use this function properly. read the docs to know more.
Its basically useful if you have input value as JS array or JS object
which can be converted to single string.
You are getting '{/"r/":/"pax/",/"c/":1 in only case if you are trying to stringify a json which already in string format.
these:
var s = ['1','2','3'];
and
var s = "['1','2','3']";
are totally different things.
If you are sending an array or json object you can even send it directly
using the code above.
for example :
send = {"r":"pax","c":1,"w":["kiwi","melon"],"g":["cat","dog"]};
ic(send);
function ic(s){
var ajaxUrl = 'im.php';
$.getJSON(ajaxUrl,
{da: s},
function(data) {
console.log (data);
});
}
make sure to handle array at php side properly.
Like if you want return json, do:
$s = $_GET["da"]; //this will be array.
var jsonObject = json_encode($s);
or you can stringify it there and then provide.
or else just send string and then use json_decode to make it json in php

Phonegap - Send array from mvc controller to Javascript using Ajax

I'm using phonegap and I'm trying to send an array encoded as json from a controller to view.
In my controller (server side):
$users = Model_Users::find(1);
$a=$users->to_array();
return json_encode($a);
In my view (into smartphone application using phonegap):
$(document).ready(function() {
$.ajax({
url: 'my/url...',
method: 'POST',
data: {
},
success: function(data) {
alert(data);
}
});
});
This working fine, infact in the view I get this alert:
data = {"name":"Jhon","surname":"Larry","age":"25"}
This work because the result of the query is only one row.
Instead when I try to get more than one query result, example:
$users = Model_Users::find('all');
$a=array();
foreach ($users as $user){
array_push($a,$user->to_array());
}
return json_encode($a);
In this case an empty response comes up, in fact I get this alert:
data = []
What is the problem?
Thanks in advance
I will try to build an answer with some tips based on what we already know thanks to the comments.
First of all now we are sure that the JSON is valid (jsonlint.com for example).
So,now, we are completely sure that the problem resides on the PHP / server-side.
My solutions:
Pay attention to not echo/return something before the value you need;
Change return with echo;
Add an exit; statement after the echoed value to be sure that no other characters will be included in the server answer;
Not exactly needed, but you can even think to set the header('Content-Type: application/json');
Debug looking at the console and using console.log instead of alert() (there are a lot of threads explaining the difference
Hope this will help!

Categories

Resources