AJAX Response to JSON Data - php

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]);

Related

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"}
]
}]

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.

Not able to pass PHP array to jquery: unexpected non-whitespace character after JSON data

Here is what I have in PHP:
$arrayresults = array();
while($popularbrushesrow = mysql_fetch_array($popularBrushes)){
$arrayresults[] = '<img class="slideImg" alt="'.$popularbrushesrow['bd_brushname'].'" title="'. $popularbrushesrow['bd_brushname'].'" src="'.$popularbrushesrow['bd_imagefilepath'].'" />';
}
echo json_encode($arrayresults);
Now, jquery:
$.ajax({
type:'GET',
url:'getDataForSlide.php',
data:"limit="+limit+"&required="+required,
dataType:"json",
cache:true,
success: function(result){
var arrayFromPHP = JSON.parse(result);
alert(arrayFromPHP);
}
})
Could someone please help me out. Whats the correct way to form an array in JSON?
The problem is likely to be this line:
var arrayFromPHP = JSON.parse(result);
Because you've specified dataType: 'json' in the ajax options, jQuery has already done the parsing for you. So doing it a second time starts out by doing toString on the array, which does a join, which results in invalid JSON.
Simply use result directly.
For example, suppose you have this JSON:
[
"Stack Overflow",
"Google"
]
Because jQuery has already done JSON.parse on it, result is an actual array. So if you then pass it into JSON.parse, the first thing that does is toString, which gives you this:
Stack Overflow,Google
...which is not, of course, valid JSON.
I would simplify your jquery....like this...
$.getJSON("getDataForSlide.php", { limit: limit, required: required}, function(json) {
console.log(json);
});
I like to use
jQuery.parseJSON(response);
And don't forget to use die(); or exit(); on php side after you echo your results, since it's a ajax call. This information can be found here: http://codex.wordpress.org/AJAX_in_Plugins

weird behaviour when parsing json coming from php in javascript

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).

JSON returned from php is [obejct Object] and jQuery.parseJSON is null

In my php file I have:
$arr[] = array("status"=>0);
echo json_encode($arr);
In my javascript, I have:
$(document).ready(function(){
initialize();
$("#searchbutton").click(function(){
var usrinput = $("#userinput").val();
$.get(
"searchpageajaxjson.php",
{searchterm: usrinput},
function(data){
searchreturned(data);
},
"json"
);
});
});
function searchreturned(data){
console.log(data);
var parsed = jQuery.parseJSON(data);
console.log(parsed);
//for (var i = 0; i < parsed.length; i++) {
// alert(parsed[i]);
// }
//
}
The console.log(data) shows [object Obejct]
and console.log(parsed) shows null
Where am I going wrong?
Edited to Add:
alert(data.status) shows undefined.
Second Edit:
I'm really grateful for all the help I've received. It's hard to pick an answer, because I'm really only able to move on from this problem due to all the help received in all the comments. I am always in awe of you kind folks who give your time to helping newbies like myself.
You're not supposed to call jQuery.parseJSON on data again. jQuery takes care of that for you already, since you used "json" as the dataType.
1. There is no reason to call jQuery.parseJSON or $.parseJSON because jQuery knows that is already a JSON object due to the "json" parameter you passed here:
$.get('source', {param:param}, function(data){ /*work with data*/ }, "json");
2. If console.log(data); is not null and you are getting some [Object Object] try to see what are the properties of that object, like this:
e.g: Explore your object:
e.g: Print value from object:
//this will output "Horror"
data.genre
Hope this helps you.

Categories