Why does ajax sometimes urlencode serialised data and sometimes it doesnt? - php

When I send serialised data to a PHP file using ajax, it is sometimes URL Encoded depending on how i do it.
Originally i had the following code which worked fine:
$.ajax({
type: 'POST',
url: 'ajax-process.php',
data: $("#sitestructure-form").serialize(),
success: function(d){$("#structureupdate").html(d);}
});
The data was sent to my PHP file and i could echo it and it looked like this.
[{"id":20,"children":[{"id":21}]},{"id":19},{"id":18,"children":[{"id":14}]},{"id":16},{"id":13,"children":[{"id":11}]},{"id":17},{"id":15},{"id":12}]
I wanted to send more than one piece of data, I called the serialized data 'order' and added 'process' to it so i updated my code to the following:
$.ajax({
type: 'POST',
url: 'ajax-process.php',
data: {
order: $("#sitestructure-form").serialize(),
process: "sitemap-reordernavigation"
},
success: function(d){$("#structureupdate").html(d);}
});
However when I retrieve the serialised data sent in 'order' the output looks like this:
data=%5B%7B%22id%22%3A20%2C%22children%22%3A%5B%7B%22id%22%3A21%7D%5D%7D%2C%7B%22id%22%3A19%7D%2C%7B%22id%22%3A18%2C%22children%22%3A%5B%7B%22id%22%3A14%7D%5D%7D%2C%7B%22id%22%3A16%7D%2C%7B%22id%22%3A13%2C%22children%22%3A%5B%7B%22id%22%3A11%7D%5D%7D%2C%7B%22id%22%3A17%7D%2C%7B%22id%22%3A15%7D%2C%7B%22id%22%3A12%7D%5D
The only way i can think of to fix this problem is to use php to urldecode it and then use str_replace to remove the 'data=' bit at the front, like so.
$data = str_replace("data=","",urldecode($_POST['order']));
How can I get this to work with AJAX though so i dont have to urldecode it?
Ive tried using a variable and setting the processData to false however that didn't seem to work.
var order = $("#sitestructure-form").serialize();
$.ajax({
type: 'POST',
url: 'ajax-process.php',
processData: false,
data: {
order: order,
process: "sitemap-reordernavigation"
},
success: function(d){$("#structureupdate").html(d);}
});
My knowledge of AJAX/Jquery is rather limited so any help would be greatly appreciated.

That's because you are feeding a serialized text string to the data attribute the first time around and jQuery does not convert it to a serialized string. The second you are assigning an object to the data attribute with the "order" attribute having the serialized text string, so jQuery basically double encodes it. For it to act as you'd like you would have to convert the form to an object and assign your "order" attribute to that object. See this post: Convert form data to JavaScript object with jQuery
// taking the example from the above link, you do this instead
order = $("#sitestructure-form"). serializeObject();

Fixed by doing the following:
$.ajax({
type: 'POST',
url: 'ajax-process.php?',
data: $("#sitestructure-form").serialize() + "&action=sitemap-reordernavigation",
success: function(d){$("#structureupdate").html(d);}
});

Related

JSON appearing as PHP array without using json_decode()

I'm using jstree on a project and attempting to save my tree to a database.
I'm obtaining the tree data as follows:
var tmp = $('#tree').jstree(true).get_json();
console.log(tmp);
This produces a JSON object in the console as I'd expect:
However when I post this to a PHP script using jquery...
$.ajax({
type: 'POST',
url: '/saveTree',
data: {'tree': tmp},
success: function(msg) {
console.log(msg);
}
});
... It is showing a PHP array of my data:
The script which I have at /saveTree displays the POST data in the tree array post key:
var_dump($this->request->data['tree']);
I assumed since the data I'm posting to the script is in JSON format I'd need to json_decode() it at the other end? If not, why not?
I've also tried adding dataType: 'json', in the ajax request but that makes no difference.
What's happening here?
Please note the PHP script at /saveTree is running in CakePHP 2.x so the line of PHP above is equivalent to var_dump($_POST['tree']) in regular PHP.
If you want send the data as string you can JSON.stringify(tmp);
tmp = JSON.stringify(tmp);
$.ajax({
type: 'POST',
url: '/saveTree',
data: {'tree': tmp},
success: function(msg) {
console.log(msg);
}
});

Javascript sending array with files to php

So i'm sending a jquery object that contains some info about a file and the actual $("#input").files[0]; item.
The jquery/javascript looks something like the following:
$.ajax({
url: '/upload/create',
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
success: function(msg) {
alert(msg);
}
});
The data variable is a JQuery object that contains info about the uploaded file and the file itself(I think), I just passed it in the object.
Is there any way to extract and save this file on the server-side with PHP?
Just remove the JSON.stringify() call and you should be good. data should be an object, which gets converted to PHP's associative $_POST or $_GET array, stringify converts it to a string.
data: data,

JS Ajax calling PHP and getting ajax call data

I have a standard javascript ajax call where I'm setting the data: to json data.
$.ajax({
type: "POST",
url: BaseUrl + "User/Login",
//url: BaseUrl + "User/Limit/1/2",
data: '{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
},
});
I was trying to get the data in php $_POST["data"] this doesn't work.
However, data: 'test={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}' works.
I was wondering is it possibly my framework or anything like that preventing $_POST["data"] from working or is this just not possible at all? Or is there something else I could use to get that data?
EDIT:
So the framework YII and the extension Restfullyii has a method to get the data it is using one line
return json_decode(file_get_contents("php://input"), true);
Which is getting all the data without the need for data= or {data: However it seems to be returning an array so Im accessing my properties like $data["userName"] where a true json object should be $data->["userName"]. Correct me if I'm wrong on any of this am I getting array in this case because I'm really sending a json string? versus a json object?
EDIT x2:
So php is making it an assoc array because it is sending true to the json_decode..
I think problem with your code is in the line where you set data: '{....}'.
It should be in json format in order to be passed properly (though it also could be in string format but you'll need to parse it on the server side)
The code below should be working right:
$.ajax({
type: "post",
url: BaseUrl + "User/Login",
data: {"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"},
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
}
});
On the server side try: $_POST['apiKey'] $_POST['appIDGiven'] and so on.
data option must be an object or serialized(e.g. "name1=value1&name2=value2") string.So you need to pass like this:
data: /*object*/{data:'{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}'},
// ^-----this is added for $_POST["data"]
or like:
data: /*serialized string*/'data={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
// ^-----this is added for $_POST["data"]
First, the data sent must be a JSON object and not a string. Remove the quotes.
Also, in your server-side, you'll better decode the input $_POST['data'] with json_decode() (see documentaion)

PHP - retrieve ajax posted json object in PHP

I'm using this function to send json to a php page:
function update_records(data) {
data = data;
$.ajax({
type: 'POST',
cache: false,
timeout: 2000,
contentType: 'application/json',
url: 'update.php',
data: data, //'data='+data+'&aid=0',
success: function() {
success_message('success');
},
error: function(){
failure_message('failure');
}
});
In firebug I can see the posted data:
[{
"postid": 66,
"values": [
"field_key=a",
"oldvalue=b",
"newvalue=c dad"
]
}]
On my php page how can I $_REQUEST the object? Or am I doing it all wrong?
i actually did solve this one using this code on my js
this is how i collected my data
i have created the object
jsonObj={"postid":postid,"value":value};
var jsonString=JSON.stringify(jsonObj);
now i sent the object using ajax
$.ajax({
type: 'POST',
url: siteurl+'/wp-content/themes/crm/modules/update_lead.php',
dataType : 'json',
data: {action:actionType,data:data},
});
and this on the target PHP file ( /wp-content/themes/crm/modules/update_lead.php)
$json=json_decode(stripslashes($_POST['data']), true);
hope this helps ...
You can use the json_decode function to decode your JSON string into an array.
JQuery has a neat function that allows us to read external and local JSON files.
jQuery.getJSON( url, [data], [callback] )
The first parameter of this function, the URL you are planning to read, is required. The second parameter is used if you need to POST data to the URL. Last but no least, the callback function, although not required, is almost always necessary.
First of all you should pass the data as "application/json" and not as "application/x-www-form-urlencoded".
...,
data: JSON.stringify(data),
...,
On the server side use json-decode() to decode the JSON encoded string into an object. This functions is very strict and relies on properly written JSON.
It tried it with the JSON you provided and it worked perfectly.
Example:
http://codepad.org/WOH2wGZv
I recommend to get rid of the surrounding square brackets if you pass only one object. I would also ensure the "values" are passed in JSON format instead of a string. This results in the following JSON:
{
"postid":66,
"values":{
"field_key":"a",
"oldvalue":"b",
"newvalue":"c dad"
}
}
On the PHP side, use $_POST['postid'] to get '66', etc. If you used type: 'GET' in your AJAX query, you should've used $_GET['postid'] on the PHP side.

how can save a string as it is in mysql database

Im trying to save this string:
~`##$%^&*()_+}{":?><,./;'[]=-|\
using a AJAX call in php. But in the database it saves as this:
~`##$%^????
this is my AJAX call
function saveComment(timesheetId,activityId,date,comment,employeeId) {
var r = $.ajax({
type: 'POST',
url: commentlink,
data: "timesheetId="+timesheetId+"&activityId="+activityId+"&date="+date+"&comment="+comment+"&employeeId="+employeeId,
async: false
}).responseText;
return r;
}
Edit: Fixed display of strings and code.
You need to in javascript call encodeURIComponent on the string with the weird characters before you send it to the server.
EDIT: Tomalak pointed out a better method.
If you want to put a variable 'text' in the data, you should run it through $.URLEncode(text) before doing so; as it is, the '&' character in the text introduces a new parameter.
jQuery supports an object as the data parameter in Ajax requests. This also does the URL encoding for you automatically:
$.ajax({
type: 'POST',
url: commentlink,
data: {
timesheetId: timesheetId,
activityId: activityId,
date: date,
comment: comment,
employeeId: employeeId
},
success: function (data) {
alert(data);
}
});
Also - you should never use synchronous Ajax requests. Always work with callback functions.

Categories