Passing JSON object to PHP with jQuery AJAX - php

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

Related

json object becoming string because double quotes are added?

I have data coming from MySql, answered from this:
How to SQL query parent-child for specific JSON format?. Basically I query it using JSON_OBJECT() which produces the result:
results <-- The column name
{"projects": "project_name": "project 1", [2nd layer stuff]} <-- the row
Awesome. MySql did the json thing for me. I make an ajax call to a PHP function to get this onto the web server.:
myPhpFunction () {
//some usual PDO code
echo json_encode($query_result);
}
On JS, I make a jQuery ajax call:
var ajaxRequest =
$.ajax({
type: 'post',
url: '../includes/ajax.php',
data: 'action' : 'myPhpFunction',
dataType: 'json'
});
ajaxRequest.done(function(data) {
//$.each(data[0].results.projects, function(key, val){
//I want to access each stuff in the object here
//}
$('#ph-projects').append(JSON.stringify(data)); //testing it out
}
The problem I'm having is by this time, my object data outputs like this:
{ "results": "{...}" }
results value is a string because of those double quotes!
This is driving me crazy. Am I missing a step to prevent this from happening?
The json_encode() is working fine as it is providing the result as a JSON object as suggested by your question({ "results": "{...}" }). And JSON_OBJECT() in PDO returning a string is fine as the name JSON suggests, its JavaScript Object Notation in a humanly readable format.
You can do on the server side:
json_encode(['results'=> json_decode($query_result['results'])]);
or on client side,
function(data){
data.results = JSON.parse(data.results);
// Your json data here
}

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

How to pass a PHP associative array to $.ajax with JSON

$.ajax seems to be broken for me:
$.ajax({url:'getGalleries.php', datatype:'jsonp',
success: function(data){
$('#galleries').html('');
$.each(data,function(key,value) {
$('#galleries').append(value);
});
},
complete: function() { loading.hide(); }
});
The php is just passing:
<?php echo json_encode(array("associative"=>"arrays","are"=>"cool")); ?>
It seems to be fine with another function that uses just regular arrays, but for some reason my jQuery is spitting out a data that is an array of every character in the JSON string when I pass it a json encoded associative array.
The PHP page is grabbing a json list of image galleries then finding the first image in each gallery. I'm making an associative array with the gallery name as the index to then pass back to my html page to show each of my galleries and a sample image.
You have two problems. One is that datatype's capitalization is incorrect; it should be dataType. Second, it isn't JSONP as far as I can see - it's JSON. So use 'json' as the dataType.
I am guessing that you need to capitalize dataType:
$.ajax({url:'getGalleries.php', dataType:'jsonp',
success: function(data){
$('#galleries').html('');
$.each(data,function(key,value) {
$('#galleries').append(value);
});
},
complete: function() { loading.hide(); }
});

Sending JSON to PHP

I'm tring to send a JSON to a PHP page via jQuery, but it doesn't work properly:
json_data = {};
json_data.my_list = new Array ();
$('#table_selected tr').each (function (i) {
json_data.my_list.push ({id:$(this).attr("id")});
});
$.post ("my_page.php", json_data, function (response) {
if (response) alert("success");
else alert("error");
});
<?php
// this is my_page.php
$json = json_decode (stripslashes ($_REQUEST['my_list']), true);
echo var_dump($json);
?>
This returns NULL to my callback, where I'm wrong?
JSON is a string representation of JavaScript objects. You're sending something that looks like this:
{my_list: [{id: 'foo'}, {id: 'bar'}, {id: 'baz'}]}
Which is not JSON. This is JSON:
'{"my_list": [{"id": "foo"}, {"id": "bar"}, {"id": "baz"}]}'
I would recommend using json2.js (more info). This can be facilitated using .serializeArray().
you don't need the echo before var_dump
json_data is a literal with an array inside that you put as parameter to the post, and will be sent as encoded array in the post request to the server.
In my_page.php you may want to look at $_POST array.
UPDATE: Ehm, I re-read your question and I'm not completely sure of what I wrote. What I said applies to GET request, and I believe also to post requests.

Categories