I am stuck with getting an array from php function located in another file to a javascript. I used the below code but nothing is happening.
PHP code:
$sprd_array;
$spread = 0;
foreach ($data as $key => $value) {
$spread =(int) ($value->ask*100000) - ($value->bid * 100000);
$spread =(float) $spread / 10000;
$spread = round( $spread, 5, PHP_ROUND_HALF_UP);
$sprd_array[] = $spread;
}
for($i = 0;$i < sizeof($sprd_array); $i++){
//echo "spread: " . $sprd_array[$i] . "<br />";
}
return $sprd_array;
}
I want to get the array in another javascript file.
javascript code:
$.ajax({
url:'jsondecode.php',
complete: function (response) {
alert("done");
},
error: function () {
alert("error");
}
});
return false;
Do it like
$.ajax({
url:'jsondecode.php',
dataType : json,
success: function (data) {
console.log(data); // This is the data you want.
},
error: function () {
alert("error");
}
});
In PHP, use the function json_encode()
to encode your objects / arrays to JSON Format. Note that setting the second argument to true will keep associative array indeces.
Also, your JavaScript code is not alright. You need to use success:
instead of complete:
. Then, you can easily convert the string back into an object using JSON.parse(yourJSONString);
.
In php change "return $sprd_array;
" to:
echo json_encode($sprd_array);