Passing a JSON object from PHP to Javascript - javascript

I generate a json object inside my php file using json_encode but when I parse it in Javascript I get error unknow token which is because when I print the returned string it is actually html code not a json string.
let's consider the simplest case:
php:
$testjson = '{"result":true,"count":1}';
echo $testjson;
js:
$.get("serverside.php", function(data, status) {
JSON.parse(data); // I get error here
});
how should I use that JSON object from php in javascript?

It probably best you create your json array a bit more dynamically in php :
$testjson = array();
$testjson['result'] = true;
$testjson['count'] = 1;
echo json_encode($testjson);

What Tanantos said is you best bet. I personally would've write it like:
$testjson = array(
"result" => true,
"count" => 1
);
echo json_encode($testjson);

PHP :
$testjson = array(
"result" => true,
"count" => 1
);
echo json_encode($testjson);
js :
$.get('serverside.php', function(json){
console.log(json);
}, 'json');
jquery-1.10.2.min

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.

strange behavior json_decode

I'm creating a json in javascript in that way
jsonArr.push({
position: 'WN',
wind: windWN,
wave: waveWN,
sea: seaWN
});
var myJsonString = JSON.stringify(jsonArr);
I'm sending it via an AJAX method with jsonData: jsonData:Ext.encode(myJsonString)
My json array looks like that when I send it :
In PHP side, I'm getting the Json and decoding it that way :
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata, true);
I tried print_r( $rawpostdata2[1]); and got '{', as the second character of the "string", and I can't understand why.
In the other side, I tried print_r($rawpostdata), cut/past the result in a $string and retest my json_decode like that :
$rawpostdata = file_get_contents("php://input");
// print_r($rawpostdata);
$string = '[{"position":"N","wind":"2","wave":"65","sea":"65"},{"position":"E","wind":"3","wave":"5","sea":"6"},{"position":"S","wind":"56","wave":"4","sea":"8"},{"position":"W","wind":"1","wave":"56","sea":"84"},{"position":"NE","wind":"5","wave":"6","sea":"65"},{"position":"ES","wind":"6","wave":"45","sea":"6"},{"position":"SW","wind":"69","wave":"8","sea":"4"},{"position":"WN","wind":"7","wave":"8","sea":"56"}]';
$rawpostdata2 = json_decode($string,true);
print_r ($rawpostdata2[1]);
It gives me the correct result !
Array (
[position] => E
[wind] => 3
[wave] => 5
[sea] => 6 )
Do you have some explanations?
EDIT : I make it working by making another json_decode
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata,true);
$rawpostdata3 = json_decode($rawpostdata2,true);
But I don't really understand...
First, you create json string:
var myJsonString = JSON.stringify(jsonArr);
Then you encode the resulting string into json again:
Ext.encode(myJsonString)
Thus, you have to json_decode() twice in PHP.
Try using $_POST instead of file_get_contets() which gives you a string.
you need to do a type cast on the result of json_decode like this:
<?php
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = (array) json_decode($rawpostdata,true);
?>
I hope this works for you.. Cheers..!!

Retrieving and using a json associative array

I use jquery and ajax to retrieve a dynamically made array made in php, like so:
$json = array();
while ($row = $stmt->fetch_assoc()) {
$json['item_'.$row['id']] = $row['name'];
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($json);
exit;
If I test the php file in browser, it outputs:
{"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"}
So far so good. But how do I use that array in jquery?
I have this jquery ajax:
$.getJSON( "json.php", function(data) {
console.log(data);
});
And testing that page in browser, it put this in console:
Object {item_3: "Simon", item_1: "Miriam", item_2: "Shareen"}
And that's ok right? Or should item_x also be in quotes?
Now, how do I USE that array in jquery?
If I try console.log(data[0]) it puts undefined
As i mentioned in comments, php associative arrays become javascript objects, which cant be accessed numericaly.
A solution would be to send an array of objects instead:
while ($row = $stmt->fetch_assoc()) {
$json[]= ['key'=>'item_'.$row['id'] , 'value' => $row['name']];
}
the in js:
data[0].key;
data[0].value;
EDIT obviously key is a misleading name in this example, better to call it something else:
$json[]= ['id'=>'item_'.$row['id'] , 'value' => $row['name']];
//js
data[0].id;
Try to use $.each() to iterate through that object,
$.each(data,function(key,val){
console.log(key,val);
});
DEMO
If you want to access it without iterating it then simply use bracket notation
data['item_3'] //Simon
Or directly access it like,
data.item_3 //Simon
Then convert it like an array as per your wish like this,
var obj = {"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"};
var convertedArray = $.map(obj,function(val,key){
var obj = {}; obj[val] = key;
return obj;
});
DEMO

Echoing a series of JSON data from php to 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 )

Accessing elements within a data structure

I've had a good search and am stumped. It may be a simple answer, but after 80 hours of work so far this week, I just can't see it...
In my app I pass some variables to a Web Service, which passes back a single structure containing key/value pairs.
$.ajax({
type: "POST",
url: "it_submitcall.php",
data: {callService: "getcall", callid: $("#callNumber").val()},
dataType: "HTML",
success: function(data){
//do stuff here
},
error: function(data){
// unable to communicate with web service stuff here
}
});
The response I get back is
Array
(
[CALLID] => 44497
[CALLERNAME] => Chris
[TEAMID] => 1175
)
How do I access the elements above in javascript? Any pointers would be greatly appreciated...
Many thanks.
On the PHP side use json_encode to turn the Array into JSON e.g:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Then on the JavaScript side use JSON.parse() to get a JavaScript object back - in your case:
success: function(data){
var obj = JSON.parse(data);
},
As #phenomnomnominal notes, you can use json_encode() on a PHP object to turn it to JSON (and, notably, json_decode() to turn it from JSON to a PHP object)
Once you've got that down, nicely, PHP and JS "hash"-like objects act a lot alike (in PHP, we call these associative arrays and in JavaScript, object literals).
In php, you access an array $your_var like this:
$value = $your_var[ 'key' ];
You can also use variables:
$key = 'key';
$value = $your_var[ $key ];
In JavaScript, it's very similar:
var value = your_var[ 'key' ];
Alternatively:
var key = 'key';
var value = your_var[ key ];
And there's one more syntax that's helpful and more efficient when you don't need variable access to a key:
var value = your_var.key

Categories