Echoing a series of JSON data from php to JavaScript, - javascript

I am having a difficulty retrieving a series of json data from php to my JavaScript, file..
Firstly, I have a series of json data stored in an array in php, and echoing each by wrapping it in the for loop to my JavaScript file,
<?php
$result = array('{"one": "test","two": "test"}','{"three": "test","four": "test"}');
for ($i = 0; $i < count($result); ++$i) {
echo $result[$i];
}
?>
in my JavaScript,
$.ajax({
url: "visualiser/visualiser_RouteList.php",
dataType: "JSON",
async: false,
success: function(data){
console.log(data);
}
});
My console does not display anything at all, not recognizing each array element as a json..
but if I send just one array element specifically, for example,
echo $result[0];
then it successfully displays,
Object {one: "test", two: "test"}
why can't I pass a series of json data in an array from php in my ajax call?

It doesn't work because you are generated malformed JSON. The output of your script is
{"one": "test","two": "test"}{"three": "test","four": "test"}
When you access the first element of the array only you get
{"one": "test","two": "test"}
Which is valid.
PHP has json_encode which will do this work for you, so your code would become
$result = array(
array('one' => 'test', 'two' => 'test'),
array('three' => 'test', 'four' =>'test')
);
echo json_encode($result);
giving the output
[{"one":"test","two":"test"},{"three":"test","four":"test"}]

Your code will output this:
{"one": "test","two": "test"}{"three": "test","four": "test"}
This is invalid JSON, so obviously will not work. (Try parsing it with JSON.parse and you'll see.)
You actually need to send the data as an array, so replace your for loop with a simple json_encode call:
echo json_encode($result);
This will output
[{"one": "test","two": "test"},{"three": "test","four": "test"}]
This is valid JSON, and can be parsed into a Javascript array.

Also can you this script
function doj($json){
$result = json_encode($json);
return json_decode($result, true);
}
$json = array(
'{"one": "test","two": "test"}',
'{"three": "test","four": "test"}'
);
$j = doj($json);
foreach($j as $k=>$v){
$extractagain = json_decode($v);
print_r($extractagain);
}
and the output is:
stdClass Object ( [one] => test [two] => test ) stdClass Object ( [three] => test [four] => test )

Related

php ajax not returning expected result, possible json decode issue

Paste the following code into PHP.
$json = '[{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}]';
$json2 = json_decode($json);
foreach($json2 as $item){
$item->total = 9;
}
foreach($json2 as $item){
print_r($item);
echo "<br>";
}
echo json_encode($json2);
The above code will display the following result. I will call this the "expected result"
stdClass Object ( [id] => 1 [quantity] => 2 [total] => 9 )
stdClass Object ( [id] => 1 [quantity] => 2 [total] => 9 )
stdClass Object ( [id] => 1 [quantity] => 2 [total] => 9 )
[{"id":1,"quantity":2,"total":9},{"id":1,"quantity":2,"total":9},{"id":1,"quantity":2,"total":9}]
Now, Following the same logic. Paste java script below
function test(){
var json = [{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}];
$.ajax({
url: base_url+"Product/ajax_test",
type: "POST",
dataType: "JSON",
data: {
'json':json,
},
success:function(data){
console.log(data);
}//end success function
});//end of ajax
}
And paste the php below, I am using codeigniter frame work if this helps
public function ajax_test(){
$json = $this->input->post('json');
$json2 = json_decode($json);
foreach($json2 as $item){
$item->total = 2;
}
echo json_encode($json2);
}
I expect the above 2 piece of code to show something similar in the console as my "expected result", but nothing shows in the console. And if I change the above code to the following
public function ajax_test(){
$json = $this->input->post('json');
foreach($json as $item){
$item["total"] = 2;
}
echo json_encode($json);
}
The above code will show result in console. the "total" property is not in the final result as if it simply gave back the original $json variable. And it is also weird I need to use $item["total"] instead of $item->total.
Question 1, What did I do wrong on the above?
Question 2, Since PHP is stateless, is there a way for me to trouble shoot ajax, by echoing out the php page in the console without json encoding it?, if this make sense.
json_decode() can decode a JSON object as either an object or an array.
$json = '[{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}]';
$json_with_objects = json_decode($json);
$json_with_arrays = json_decode($json, true);
echo $json_with_objects[0]->quantity;
echo $json_with_arrays[0]["quantity"];
var_dump($json_with_objects);
var_dump($json_with_arrays);
Presumably, though we can't know since you don't provide it, your code $this->input->post() is decoding with associative arrays instead of objects.

PHP to JSON Array Output is Wrong

What I am trying to do doesn't feel difficult, but for some reason I can't seem to find the correct way to ouput this JSON array, from php.
PHP code:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$a = array();
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP DateTime
$a = array(
"time" => $dt->format('Y-m-d H:i:s'),
"signal" => $row['signal'],
"symbol" => $row['symbol'],
"price" => $row['price'],
"timeframe" => $row['timeframe'],
"epoch" => $row['time']);
echo json_encode($a, JSON_UNESCAPED_SLASHES);
}
Output:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
{
"time":"2016-11-14 17:07:59",
"signal":"Sell",
"symbol":"GBPJPYecn",
"price":"135.13200",
"timeframe":"M1",
"epoch":"1479143279"
}
The correct output should have },{ NOT }{ between each object.
What I am ultimately trying to do:
function getTrades(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#trades").html('<span class="tradesignal"><!-- span class="signalarrowup"></span-->'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
});
}
//alert(response);
console.log(response);
}
});
}
Each {json},{json} object will have its data printed into a span on an html page.
Appreciate the guidance!
Try creating a results array and push each one of the objects there, then after the loop finishes, convert the array to json and print it.
example:
$results = array();
$i = 0;
while($row = mysqli_fetch_array($result)){
//your code here
$a = array("time" => ....);
$results[] = $a; //this will add $a to $results
}
echo json_encode($results, JSON_UNESCAPED_SLASHES);
Just to add a little more explanation in addition to the code the other answers are suggesting. The problem is, you aren't outputting a JSON array. Each time you do
echo json_encode($a, JSON_UNESCAPED_SLASHES);
inside your loop, you output a valid JSON object like:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
However, when you output the subsequent objects, getting a result like
{
"time": ...
}
{
"time": ...
}
You no longer have valid JSON. Even though each of the individual objects is valid, concatenating them together isn't. Simply adding a comma between the objects will still not make it valid. In order to produce an actual JSON array, the comma separated objects will need to be enclosed in square brackets like this:
[
{
"time": ...
},
{
"time": ...
}
]
That's why you need to add each of the arrays you're creating in the loop to an outer array and then json_encode the whole thing after the loop. The outer PHP array will become the outer JSON array you need.
As Xorifelse said, you want to put the data in an array, and then call json_encode on the array. Here is a code that should work:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP Date
$a[] = array("time" => $dt->format('Y-m-d H:i:s'), "signal" => $row['signal'], "symbol" => $row['symbol'], "price" => $row['price'], "timeframe" => $row['timeframe'],"epoch" => $row['time']);
}
echo json_encode($a, JSON_UNESCAPED_SLASHES);

How can I convert this JSON from PHP to a Javascript array

I am trying to assign a json array to a javascript array so that my JS functions can access the array.
So I have an ajax call to MySQL db to get a JSON array of data:
var data = [];
$.ajax({
type:"post",
url:"position.php",
dataType:'json',
success:function(jsonarray){
data=$.parseJSON(jsonarray);
}
});
position.php:
<?php
include 'dbconnect.php';
$sql = "SELECT pid, posX, posY FROM posTable;";
$result = $conn->query($sql);
$myrows = $result->num_rows;
$return=array();
if ($result->num_rows>0){
while($row=$result->fetch_assoc()){
$return[]=array((int)$row['pid'],(int)$row['posX'],(int)$row['posY']);
}
}else{
echo "[]";
}
echo json_encode($return);
$conn->close();
?>
This gives an output like this:
[[1,749,1000],[2,855,986],[3,955,946],[4,1037,934],[5,1111,912]]
And from this I want the following two dimensional array so that I can access its memebers in this form:
data[i][j]
data => [[1,749,1000],[2,855,986],[3,955,946],[4,1037,934],[5,1111,912]]
However when I execute the code I keep getting the following error:
Uncaught SyntaxError: Unexpected token , in JSON at position 1
What am I doing wrong?
jQuery will automatically parse a JSON response before populating the success function's first argument.
$.parseJSON(jsonarray); calls toString() on your array and then tries to parse it as JSON, which it isn't (because Array.prototype.toString() doesn't convert to JSON).
Just don't try to parse it again.

PHP json_encode function is not working on ajax call

In page load I am calling this function
function myFunction(selectedCinemaID) {
$.ajax({
type: "POST",
url: "show_details.php",
data: {cinema_id: selectedCinemaID }
}).done(function( show_list ) {
console.log(show_list.length);
});
And my code in show_details.php
$query = "SELECT * FROM `show` WHERE cinema_id=2;";
$result = mysql_query($query);
if($result){
$show_list = array();
while($row = mysql_fetch_array($result)){
array_push ($show_list, array($row['id'], $row['cinema_id'], row['show_time']));
}
echo json_encode($show_list);
} else {
echo mysql_error();
}
In my database I have only two row and three column but the length showed in the console is 64. But according to the database length should be 2. console.log(show_list) output [["2","2","2014-11-01 01:00:00"],["3","2","2014-11-01 04:00:00"]] but it seems everything here is treated as an array element or string. What is wrong in this code?
You haven't told jquery that you're sending JSON. As such, it'll treat the json text that the server is sending as text. That means
console.log(show_list.length);
is outputting the length of the json string, not the count/size of the array you're building in PHP.
You need either
$.getJSON(....);
or
$.ajax(
dataType: 'json'
...
)
However, note that if your mysql query fails for any reason, then outputting the mysql error message as your are will cause an error in jquery - it'll be expecting JSON, and you could potentially be sending it a mysql error message, which is definitely NOT json.
Once you switch to JSON mode, you should never send anything OTHER than json:
if (query ...)
output json results
} else {
echo json_encode(array('error' => mysql_error()));
}
The JavaScript function .length is counting the length of the entire serialized array string. You need to parse it first:
.done(function( show_list ) {
var data = JSON && JSON.parse( show_list ) || $.parseJSON( show_list );
console.log( data.length );
});
Thanks,
Andrew

Loop through PHP associative array in javascript or jquery

I have the following PHP associative array output as a response to jquery post request:
Array
(
[0] => Array
(
[user] => 25
)
)
How can iterate through the above PHP associative array in javascript or jquery? Is this possible? or should I print the output of PHP in another way? I have access to the PHP as well
In PHP just echo using json_encode:
$array = array(array('user' => 25));
echo json_encode($array); // [{"user":25}]
In Jquery:
var data = $.parseJSON(jsonString); // '[{"user":25}]'
console.log(data[0].user); // 25
Here's what I use in a similar application:
PHP:
header("Content-Type: application/json");
if ( $_REQUEST["jsoncallback"] ) {
$callback = htmlentities( $_REQUEST["jsoncallback"] );
}
$output = json_encode( $array );
if ( $callback ) {
$output = $callback . "(" . $output . ")"; // I know the variables can be embedded in the strings, I don't care, I like it this way.
}
echo $output;
Javascript:
var getURL = "http://www.example.com/script.php?jsoncallback=?";
jQuery.ajax({
dataType: "json",
url: getURL,
success: function(data){
var obj = jQuery.parseJSON( data );
// now you can loop through the data object
}
});
For the looping part, this question/answer might be helpful: How to Loop through plain JavaScript object with objects as members?

Categories