YumYumYum YumYumYum - 5 months ago 14
Ajax Question

Javascript - not able to parse the JSON or string sent via PHP

How do i get the json data in Javascript?

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

$result=curl_exec ($ch); // it has json data

curl_close ($ch);

/* PHP unit test - shows the data is available and it works
$obj = json_decode($result, true);
foreach($obj as $k=>$v) {
echo $k . ' ' . $v . '<br/>';
}
*/

/* But, from PHP i need to send the data to Browser on Ajax/GET request*/
$obj = json_decode($result, true);
echo $obj;
//if i do not use json_decode and only do echo $result; then still
//javascript is unable to parse the json


So when Javascript is calling that PHP method, its failing to decode as readable format:

$.get(submit_url + '/login?', {
code_please: '007',
}, function(data_please) {

// ------------------------------FAIL to READ
alert(data_please);
alert(data_please[0]);
alert(data_please.id);
//var duce = jQuery.parseJSON(data_please);
//var art1 = duce.email;
//for(oooi in data_please.db) { data_please.db[oooi].id++ }

});


Output: Array

Answer

If your getting a JSON encoded string from the curl response you don't need to call json_decode on it, just echo the string out. json_decode will convert it into a PHP array which is not what you want.

Also you should call your own endpoint using $.getJSON as this will convert the JSON into an object you can use with javascript automatically.