weird behaviour when parsing json coming from php in javascript - php

I have a weird problem with parsing a JSON response coming from php source (symfony2). This is probably something very trivial but I'm not very skilled in javascript so have lost many hours on this already.
I have a serialized php-array in my db, which I unserialize and then convert to JSON.
$response->setContent(json_encode(unserialize($onderdeel->getArticles())));
On the client I just use jQuery to parse the json data.
$.ajax({
......
success: function(data){
articleObject = jQuery.parseJSON(data);
}
});
However this gives me some weird results, some of the values are set to undefined while they should have a value. However some of the values are ok.
This is the raw result I get from the php script before it get's parsed:
{
"onderdeel":{
"onderdeel_id":"1546",
"onderdeel_type":"overgordijnen160",
"onderdeel_naam":"",
"onderdeel_opmerkingen":"",
"berekend_prijs":"0",
"status":"",
"active_artikel_id":"0",
"naam_ruimte":"",
"opmerkingen":""
},
"artikels":[
{
"ruimte":"",
"opmerkingen":"",
"korting":"",
"berekend_aantal_banen":"2",
"aantal_banen_zelf_ingegeven":"",
"berekend_hoeveelheid":"400",
"berekend_multiplicator":"1.9",
"berekend_valide":"",
"berekend_prijs_met_korting":"0.00",
"berekend_prijs":"20040040.00",
"stap2":{
"valide":"valide",
"hoogte":"100",
"breedte":"100",
"banen":"stel",
"stof":{
"id":"9",
"naam":"AGRA",
"modelnummer":"123456",
"stofbreedte":"140.00",
"rapporthoogte":"100.00",
"kleur":"nul",
"prijspermeter":"100.00",
"wasvoorschriften":"COOL WASH COOL IRON",
"stock":" "
},
"railtype":{
"id":"7",
"naam":"rails type 1",
"modelnummer":"RT-2",
"stock":"200.00 stuks",
"rapporthoogte":"null",
"prijspermeter":"null",
"wasvoorschriften":"null"
}
},
"maakwijze":{
"status":"",
"maakwijze_type":"lint",
"plooi":"",
"retour_plooi":"",
"cm_plooi":"",
"hoofdje":"100",
"berekende_string":"LINT > gewone voering",
"voering_string":"gewone voering",
"voering":{
"voering_id":"",
"voering_prijs":"",
"voering_onderdeel":"",
"voering_type":""
},
"voering_aan":"true",
"confectie":{
"confectie_id":"2",
"confectie_prijs":"10000000.00",
"confectie_zoom":"25.31",
"confectie_onderdeel":"OG < 160",
"confectie_type":"LINT > gewone voering"
},
"valide":"valide",
"loodjes":"loodjes"
},
"prijs":{
"prijs_valide":"",
"prijs_korting":"",
"prijs_plaatsing":"",
"prijs_berekend_voor_artikel":"",
"prijs_berekend_voor_artikel_met_korting":"",
"prijs_berekend_stofprijs":"40000",
"prijs_berekend_confectieprijs":"20000000",
"prijs_berekend_prijslood":"40",
"prijs_berekend_voering":"0",
"prijs_railtype_prijs":""
}
}
],
"onderdeel_naam":"",
"onderdeel_opmerkingen":""
}
However after I parse it this is the result:
For example artikels.0.maakwijze.maakwijze_type is set to undefined while in the raw json it is set to 'lint'.
The weird thing is that if I just copy the raw json to the chrome console and parse it with the same function jQuery.parseJSON('copied text') all values are ok
I also replaced the jQuery.parseJSON with the standard JSON.parse , but this gave me the same result
Any ideas what causes this?
Thanks!!

On the client I just use jQuery to parse the json data.
$.ajax({
......
success: function(data){
articleObject = jQuery.parseJSON(data);
If your server is returning Content-Type: application/json, data will already be a parsed object. You don't want to parse it again.
Without the jQuery.parseJSON(data), it works for me (source).

Related

AJAX Response to JSON Data

I have a JSON response, and the formatting is stumping me:
{
"SearchResults": [
{
"SearchItem": "409885340",
"Shipment": {
"DRAvail": true,
"ProNumber": "409885340",
"PickupNumber": "24861628",
"CustomerNumber": "688926",
"BOLNumber": "100982156",
"BOLReceived": true,
"PODReceived": false,
And so on and so forth. Now when I return success in my AJAX (below):
success: function(data) {
alert(data);
alert(JSON.parse(data.SearchResults[0]));
The alert data returns:
{"SearchResults":[{"SearchItem":"409885340","Shipment":{"DRAvail":true,"ProNumber":"409885340","PickupNumber":"24861628","CustomerNumber":"688926","BOLNumber":"100982156","BOLReceived":true,"PODReceived":false,"PONumber":"04272018"...
But on the next line (where it is parsed), it returns this in the console:
TypeError: data.SearchResults is undefined
I know it's likely me being tired, but I'd appreciate any help in trying to get this to work...
Thanks
You need to parse first, the get then element you want:
//mind the closing parenthesis after data
alert(JSON.parse(data).SearchResults[0]);
IF your ajax response type is application/json you dont need to parse it
alert(data.SearchResults[0]);
will do
else
if return data is string you need to parse it and than get value
var parsedData = JSON.parse(data);
alert(parsedData.SearchResults[0]);

Passing JSON object to PHP with jQuery AJAX

I have 3 different JSON objects I want to concatenate and send over to a PHP file with jQuery AJAX. I can retrieve the JSON object in the PHP file, but cannot figure out how to loop through the results.
Here's what I have so far:
//my 3 JSON objects:
var json_obj_1{
"test1_key":"test1_val",
"test2_key":"test2_val",
"test3_key":"test3_val"
}
var json_obj_2{
"test4_key":"test4_val"
}
var json_obj_3{
"json_arr":[
{
"test1":"test2",
"test3":"test4"
}
]
}
//concat these to send over to the PHP file:
var my_json_obj = json_obj_1.concat(json_obj_2);
//I found if I didn't stringify obj_3 they didn't concatenate for some reason
my_json_obj = my_json_obj.concat(JSON.stringify(json_obj_3));
//my_json_obj now looks like this:
{
"test1_key":"test1_val",
"test2_key":"test2_val",
"test3_key":"test3_val"
}
{
test4_key: test4_val
}
{
"json_obj_3":[
{"test1":"test2","test3":"test4"}
]
}
Based on this question: Sending JSON to PHP using ajax, I don't stringify the final JSON object.
Here's the AJAX call to the PHP file:
$.ajax({
url: 'my_php_file.php',
data: {my_json_data: my_json_obj},
type: 'POST',
async: false,
dataType: 'json',
cache:false,
success:function(data, textStatus, jqXHR){
console.log('AJAX SUCCESS');
},
complete : function(data, textStatus, jqXHR){
console.log('AJAX COMPLETE');
}
});
This is what it looks like when retrieved in my PHP file:
echo $_POST['my_json_data'];
//outputs:
{
"test1_key":"test1_val",
"test2_key":"test2_val",
"test3_key":"test3_val"
}
{
test4_key: test4_val
}
{
"json_obj_3":[
{"test1":"test2","test3":"test4"}
]
}
Here's where I run in to problems. I want to be able to loop through this in a foreach. From what I have read (php: loop through json array) I have to decode the JSON object. However when I do this and loop through the results I get: " PHP Warning: Invalid argument supplied for foreach() ".
Even if I stringify the JSON object before sending it over to the PHP file I get the same problem. I have been banging my head against a brick wall for hours with this. Any help will be massively appreciated.
Thanks in advance.
Solved:
I was going wrong when concatenating my JSON objects following this question: Merge two json/javascript arrays in to one array. Instead I just put them together like so:
my_json_obj = '['+json_obj_1+','+json_obj_2+', '+JSON.stringify(json_obj_3)+']';
I then use json_decode in my PHP file which works a treat. http://json.parser.online.fr/ was invaluable in debugging my dodgy JSON. A great tool for JSON beginners.
You should be stringifying the whole object, try the following:
var my_json_obj = json_obj_1;
$.each(json_obj_2, function(key,value){
my_json_obj[key]=value;
});
$.each(json_obj_3, function(key,value){
my_json_obj[key]=value;
});
Ajax request:
data: {my_json_data: JSON.stringify(my_json_obj)},
PHP:
print_r(json_decode($_POST['my_json_data']));
As you say you need to decode the JSON, but your JSON is not well formed so I think the decode function is failing which causes the foreach error. There needs to be a , between objects, there's missing quotes around test4_val and it needs to be inside a singular object/array
You can check your JSON is wellformed at:-
http://json.parser.online.fr/
I think you want it to look more like:-
[{
"test1_key":"test1_val",
"test2_key":"test2_val",
"test3_key":"test3_val"
},
{
"test4_key": "test4_val"
},
{
"json_obj_3":[
{"test1":"test2","test3":"test4"}
]
}]

json_encode returns array as a string when posting data with jquery.get()

Hello I have a problem with my ajax request in jquery.
When I use my get request without sending any data the response is as expected, I receive my array and can access the values:
$.get(
loadUrl,
function(data) {
useReturnData(data);
},
"json"
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
This works as expected and I recieve my value of "528" being my leftPlayer[4] value.
But when I change my request to send a piece of data to php in the request like so:
$.get(
loadUrl,
{ type: "left" })
.done(function(data) {
useReturnData(data);
},
"json"
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
My data received seems to be in string format to javascript.
My alert prints "5" (the 4th character if the array was a string)
When alerting leftPlayer. I find that in the first request in which I send no data the variable is printed as: 355,355,355,355,528,etc...
Whereas in the second request in which I DO send data it prints as:
[355,355,355,355,528,etc...]
Notice the []. It isn't recognised as an array.
The php file it accesses has absolutely no changes in each request, as I am testing at the moment. The data sent isn't even used in the php file at the moment.
Any ideas where I'm going wrong?
I've fixed my problem.
Like what "nnnnnn" said in his comment I'm passing my "json" parameter to the .done() function instead of the $.get() function.
I couldn't seem to get it to correctly view it as JSON though so I used the easiest method:
$.getJSON(
loadUrl,
{ type: "left" },
function(data) {
useReturnData(data);
}
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
Using $.getJSON instead does like what it says and expects JSON to be returned as default.

Reading JSON data (created by PHP) via jQuery Ajax results in "parserror"

I create JSON-data with the following php code:
if($res = $db->query('Select row1 from table1')){
while($row = $res->fetch_row()){
$json[] = $row;
}
}
sort ($json);
$json = json_encode($json);
echo $json;
The result is [["1"],["2"],["3"]].
When I try to fetch this data with jquery ajax
<div id="output">JSON will be put here</div>
<script language="javascript" type="text/javascript">
$(function () {
$.ajax({
url: 'json.php',
dataType: 'json',
data: '',
error: function(request,error) {
alert(error);
},
success: function(data) {
var json = data[0];
alert(json);
$('#output').html(json+", ");
}
});
});
it says: "parseerror".
I searched a lot (here at Stack Overflow), but my jQuery version seem to be right (1.7.2) and reformating the JSON-outpu did not help (I deleted the opening brackets and tried a lot of other things).
Any ideas?
Parse the data return in ajax result,
var retData= JSON.parse(data);
You should check if you get an object before using it:
if(typeof data != 'object')
data = $.parseJSON(data);
Sometime it is interpreted as a string and you have to convert it first
I don't think you need to push it in an array. Your query is already an array. SO try to only json_encode() and that alert the data what you get and try to access the data by using data.somevariable( at least that is how I access my json data in the ajax).
Hope it helps
Verify the content type of the response header (you can see this in any modern browser's network console). It needs to be coming back as application/json. Any other type may cause your Javascript to fail. Before echoing the JSON in your PHP file, try adding:
header('Content-Type: application/json');
This will explicitly and correctly set the response content type. Keep in mind, this in contingent upon your return string being valid JSON in the first place, which it seems to be.

Javascript post to PHP and get back an array?

So i have this piece of javascript, it posts to foo.php with value val, gets back data, empties the container and call function graph which will fill the container with a new chart.
$.post("foo.php", {val: val}, function(data){
if(data.length >0) {
$('#container').html('');
graph(data);
}
});
in foo.php, how do I make it pass back an array instead of string? at the moment I just have an echo in foo.php that echos the data delimited by a comma, ie: 1,2,3,4,5. then in the graph function I have a split(',' data) that creates an array for later use.
I mean, all this works fine, I'm just wondering if I can avoid the split step and have foo.php return an array directly.
thanks!
That's what json_encode is for:
echo json_encode( $array );
Just remember to set JSON headers, so that jQuery will know to parse the returned data as JSON. If you don't, you'll have to specify that in your jQuery AJAX call as follows:
$.post("foo.php", {val: val}, function(data){
if (data.length > 0) {
$('#container').html('');
graph(data);
}
}, 'json'); // <-- Here you're specifying that it'll return JSON
json_encode your array in PHP and jquery can easily parse your JSON encoded data.

Categories