Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here
Related
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);}
});
I am trying to pass an array via ajax to a remote php script for execution.
This is a snippet from what i tried
$arr=["12","13"];
$.ajax({
url:"script.php",
data:{"arr":$arr}
success: function(data){console.log(data);},
error:function(data){console.log("error in xhr");},
complete:function(data){},cache: false,type: "POST",dataType: 'json'
})
<?php
$return['arr']=json_decode($_POST['arr']);
echo json_encode($return);
?>
I caught the error in firebug : json_decode() expects parameter 1 to be string, array given.
However when i process the same php script alone.. it works fine!
Where am i going wrong and what would be the best way to handle the array ?
Try this,
data:{"arr":JSON.stringify($arr)}
let me know is this helpfull?.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the content-type so your server understands it's JSON.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
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)
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.
I got the error:
request failed: URI too long (longer than 8190)
I've seen other posts on StackOverflow for this one. Those posts recommend:
Not changing Apache settings (agree)
Using post, not get
Not using jsonp with post
I'm using jQuery's AJAX to POST:
$.ajax({
url: "test.php",
dataType: "json",
data: paras,
type: "POST",
success: function(ret){callback(ret);}
});
It's my impression you can use json just not jsonp. Correct? If so, why might I still be getting the error?
You should try setting proccessData to false.
From the docs:
By default, data passed in to the data option as an object
(technically, anything other than a string) will be processed and
transformed into a query string, fitting to the default content-type
"application/x-www-form-urlencoded". If you want to send a
DOMDocument, or other non-processed data, set this option to false.
so to prevent the data being added to the url:
$.ajax({
url: "test.php",
dataType: "application/json",
data: paras,
type: "POST",
proccessData: false, // this is true by default
success: function(ret){callback(ret);}
});
Honestly, I thought this was automatic, but since your url is too long it's worth a shot.
I ran into this issue when using jQuery to submit large forms, and was able to solve it by adding this plugin.
For example, using the following code to submit the form after adding the plugin resolved the issue for me:
$(formSelectorHere).ajaxSubmit({
url: myURL,
type: 'post',
contentType: "multipart/form-data",
data: $(this).serialize(),
success: function(data) {
function(data) {
//success code here//
}
});
If you're not using this to submit a form, this may not be relevant to you and won't solve your problem, but that's the most common situation where this issue appears, so I figured it was worth mentioning. (The plugin should also be able to submit a form using JSON, but haven't personally tested it).