Using jQuery and AJAX to pass JSON data to PHP - php

I have an AJAX call using the following;
$.ajax({
type: "POST",
url: "php/customheader.php",
data: {
update: 1,
header : {
1 : custom[1].header,
2 : custom[2].header,
3 : custom[3].header,
4 : custom[4].header
},
header_key : {
1 : custom[1].key,
2 : custom[2].key,
3 : custom[3].key,
4 : custom[4].key
}
},
dataType : 'json',
success: function(data) ajaxSuccessCallback(this_dialog, data)
});
On the PHP end, I am struggling to get this data into a proper associative array to use in loops etc. I've tried;
$_POST['update']
which returns 1. So I know how to use JSON -> PHP when the data is not in an associative/multidimensional array.
Calling this however;
$_POST['header[1]']
returns nothing.
What is the best method for getting this multidimensional data into a proper format for iteration within PHP?
Thanks,

Did you try $_POST['header']?

First convert it to json text first on the client side
e.g
var obj = {'update':1,'header':{'key1':custom[1].key,'key2':custom[2].key,'keyN':custom[N].key},...}
var jsonstring = JSON.stringify(obj);
after setting up the object, use the stringify function to convert it to JSON string (please read more about the json format, it would help you in setting up the object correctly), send it with $.get() or $.post() (makes ajax request easier)
//example
$.get("serverside.php",{'data':jsonstring});
then on the server side lets say you used $.get() on the client side , you'll say
$str = $_GET['data'];
$Obj = json_decode($str,true);
then you can now say:
echo $Obj['update'];
I hope this helps, and be warned, there's lot of debugging ahead, so make good use of the internet

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

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.

How to unserialize a serialized array sent to the server using GET method with a jQuery Ajax call?

I'm trying to deserialize an array from an URL I've sent from a JQuery Ajax call to a PHP script in the server.
What I have done
I've been sending variables with values to the server successfully with jQuery Ajax this way:
// A simple text from an HTML element:
var price = $("#price option:selected").val();
// Yet another simple text:
var term1 = $('#term1').val();
Then I prepare the data to be sent via Ajax this way:
var data = 'price=' + price + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString
And send it with jQuery Ajax like this:
$.ajax({
url: "script.php",
type: "GET",
data: data,
cache: false,
dataType:'html',
success: function (html) {
// Do something successful
}
});
Then I get it in the server this way:
$price = (isset($_GET['price'])) ? $_GET['price'] : null;
$term1 = (isset($_GET['term1'])) ? $_GET['term1'] : null;
And I'm able to use my variables easily as I need. However, I need to do this with an array.
Main question
Reading a lot, I've managed to learn the professional way to send an array to the server: serialize it! I've learnt this way to do it with jQuery:
var array_selected = [];
// This is used to get all options in a listbox, no problems here:
$('#SelectIt option:not(:selected), #SelectIt option:selected').each(function() {
array_selected.push({ name: $(this).val(), value: $(this).html().substring($(this).html().indexOf(' '))});
});
var array_serialized = jQuery.param(array_selected);
// If I alert this I get my array serialized successfully with in the form of number=string:
//Ex. 123=stringOne&321=StringTwo
This seems to be right. I add this to the data as before:
var data = 'price=' + price + '&' + array_selected + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString&123=stringOne&321=StringTwo
How do I reconstruct (unserialize) my array in the server? I've tried the same as before:
$array_serialized = (isset($_GET['array_serialized'])) ? $_GET['array_serialized'] : null;
with no success! Any ideas why? How can I get my serialized array passed this way in the server as another array which PHP can handle so I can use it?
Or am I complicating my life myself needlessly? All I want is to send an array to the server.
If you name a variable with [] in the end of it, it will create an array out of the values passed with that name.
For example, http://www.example.com/?data[]=hello&data[]=world&data[]=test, will result in the array $_GET["data"] == array('hello', 'world', 'test'); created in PHP.
In the same way, you can create an associative array in PHP: http://www.example.com/?data[first]=foo&data[second]=bar will result in $_GET["data"] == array("first" => "foo", "second" => "bar");
BTW, you might be interested in using jQuery's .serialize() or .serializeArray(), if those fit your client side serializing needs.
I'm not too knowledgeable with PHP, but I think you may have overlooked something pretty simple, <?--php unserialize($string) ?>.

Parsing PHP/JSON data in Javascript

I'm trying to communicate AJAX, JSON to PHP and then PHP returns some data and I'm trying to parse it with Javascrpt.
From the php, server I return,
echo json_encode($data);
// it outputs ["123","something","and more something"]
and then in client-side,
success : function(data){
//I want the data as following
// data[0] = 123
// data[1] = something
// data[3] = and more something
}
But, it gives as;
data[0] = [
data[1] = "
data[2] = 1
It is reading each character but I want strings from the array, not individual characters. What is happening here? Thanks in advance, I am new to Javascript and JSON, AJAX.
JSON.parse(data) should do the trick.
Set the dataType property of the ajax call to json. Then jQuery will automatically convert your response to object representation.
$.ajax({
url : ...,
data : ...,
dataType : "json",
success : function(json) {
console.log(json);
}
});
Another option is to set headers in PHP so that JQuery understand that you send a JSON object.
header("Content-Type: application/json");
echo json_encode($data);
Check this one... Should Work
success : function(data){
var result = data;
result=result.replace("[","");
result=result.replace("]","");
var arr = new Array();
arr=result.split(",")
alert(arr[0]); //123
alert(arr[1]); //something
alert(arr[2]); //......
}
You did not shown function in which you parse data. But you shoud use
JSON.parse
and if broser does not support JSON then use json polyfill from https://github.com/douglascrockford/JSON-js
dataArray = JSON.parse(dataFomXHR);
I'm not sure if this is what you want but why don't you want php to return it in this format:
{'item1':'123','item2':'something','item3':'and more something'}
Well to achieve this, you'll need to make sure the array you json_encode() is associative.
It should be in the form below
array("item1"=>123,"item2"=>"something","item3"=>"more something");
You could even go ahead to do a stripslashes() in the event that some of the values in the array could be URLs
You could then do a JSON.parse() on the JSON string and access the values
Hop this helps!

Print array from PHP in the jQuery

How can print date and age (in following array) separate by $.ajax()?
php:
$array = array(
'date' => 2011/9/14,
'age' => 48,
);
return $array // this send for ajax call in the jQuery
I want this output by jquery:2011/9/14 & 48
Use $.ajax Methods and setting parameter dataType to JSON for receive data type JSON from PHP file.
Jquery Code:
$.ajax({
url: "getdata.php",
type: "post",
dataType: "json",
success: function(data){
alert("Date:" + data.date + "\n" + "Age:" + data.age);
}
});
if your array data contains string make sure it's closured with quote then make data type JSON with json_encode() function.
PHP Code (getdata.php):
$array= array('date'=>'2011/9/14','age'=>48);
echo json_encode($array);
Echo the encoded array in php page say mypage.php
using
echo json_encode($array);
And use jQuery.getJson in the client side
$.getJSON('mypage.php', function(data) {
alert(data['date']);
alert(data['age']);
});
You need to encode the array as a valid JSON string using the PHP function json_encode. You can then use the jQuery function $.parseJSON to convert it into a JavaScript object. From there you'll be able to do whatever you want with it.
If you do this, you'll end up with an object like:
ajaxDataObj = {
date: '2011/9/14',
age: 48
}
**Edit**
Please see stratton's comment below about using $.getJSON for a more compact solution.
Also, Ben Everard's comment on your original post about using echo rather than return is critical.
You can't just return $array to the browser, the result will be "Array" as string.
YOu have to use return json_encode($array); which returns a string that could be parsed by browser.
If the server-client communication is working alright, then you should do something like this on the client side:
$.ajax({
//configuration...
'success':function(response){
var dateAge = response.date+' & '+response.age;
//put or append the string somewhere.
}
});

Categories