JQuery: Send JSON Objects with an Ajax Request
Through my blog, I will discuss about sending JSON objects with ajax request using JQuery. We have number of functions in jQuery to kick-off an ajax request. But for sending JSON objects along with the request, I chose jQuer.ajax(). It takes various parameters url, type, data, dataType, beforeSend etc. Its API can be found here.
Lets look at example given below:
jQuery.ajax({ url: , type: "POST", data: {name: "amit", id:1 }, dataType: "json", beforeSend: function(x) { if (x && x.overrideMimeType) { x.overrideMimeType("application/j-son;charset=UTF-8"); } }, success: function(result) { //Write your code here } });
The above example works for simple JSON object. Now lets see how we can send JSON objects list as given below:
var jsonObjects = [{id:1, name:"amit"}, {id:2, name:"ankit"},{id:3, name:"atin"},{id:1, name:"puneet"}]; jQuery.ajax({ url: , type: "POST", data: {students: JSON.stringify(jsonObjects) }, dataType: "json", beforeSend: function(x) { if (x && x.overrideMimeType) { x.overrideMimeType("application/j-son;charset=UTF-8"); } }, success: function(result) { //Write your code here } });
If you notice, for sending my json objects it has not been written directly as data: jsonObjects. As it expects the JSON object passed to it written as key value pair. So we made students the key. And since we have json objects stored in a variable, we need to expand the json objects list using stringify(), otherwise it would be sent as a java script object.
Now on the server we can parse the JSON object, and use it as the list of objects of type map. For example
//this code is written in grails import grails.converters.JSON; List students = JSON.parse(params.students) //students in request params is parsed to json objects and stored in the List println "Student id: " + students[0].studentId //first element of the students list is accessed as a map holding a key studentId
Stay tuned for more updates and visit our product engineering innovations.
It’s ok. but If I will have to receive this object from server then which kind of parameter should I assign to JesonResult??
simple but good
Thanks for the post. I have been searching for this current solution for almost 3 and half hours. Now i got it. Thanks a lot
Thanks a lot Amit. You saved the day. I was having serious trouble receiving the data as I was not using JSON.strigify(). Your solution worked like charm.
Hi, Can u tell me how to send parameters to the REST web service
First of all thanks.excellent work for me.
Thanks for sharing, man! It really worked for me!
Excellent work, thank you for sharing this with everyone.
Thanks for sharing Amit!
how to send request from one web application to another web application using ajax and json
Incredible! Many thanks! I desired to produce in my small
website or something that is. Can one include a
fragment of your respective article in order to my site?
just adding the following property worked for me:
contentType: “json”
I have a json of the following format which I need to send in the Ajax request through POST method:
{
“gbus”: [
{
“code”: “*”
}
],
“regions”: [
{
“code”: “*”
}
],
“offices”: [
{
“code”: “*”
}
],
“contracttypes”: [
{
“code”: “*”
}
],
“jobnumbers”: [
{
“code”: “*”
}
],
“disciplines”: [
{
“code”: “*”
}
]
}
Its not working for me, giving 500 error always when I try to submit it.
Please suggest if you have any idea.
Another way of sending complex(more than key value pair) json objects is via request body.To achieve this just set data to Json.stringify(jsonObjects)and set the processData flag to false to prevent automatic processing and transformation of the data into a query string. Also set contentType to “application/json” to make sure the server knows whats in the request body and handles is accordingly.
var jsonObjects = [{id:1, name:”amit”}, {id:2, name:”ankit”},{id:3, name:”atin”},{id:1, name:”puneet”}];
jQuery.ajax({
url: ,
type: “POST”,
data: JSON.stringify(jsonObjects),
processData:false,
contentType : “application/json”,
dataType:”json”
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType(“application/j-son;charset=UTF-8”);
}
},
success: function(result) {
//Write your code here
}
});
And on the server side just get the data as request.getReader() or request.getInputStream() and parse it with the api of your choice.
@jacob,
I think you can use jQuery.getJson() http://api.jquery.com/jQuery.getJSON/
Regards
this is what i need, but i want to know one more thing, like i want to send this json data to the php page,, then how do i receive the json data that is send through the ajax request??
for example if we send the data normally means without any json format the we will $_GET[] to get the data..
thanks
Hi,
Thanks for your Example ^^
This is just great and work well on IE, but it do not work on Chrome and Firfox!
I think this is a problem about cross domain!
Could you tell me the way to sole this problem!
Expect your response soon!
Thanks so much!
Outstanding post ! well done, Amit Loon !
Thanks that solved my issue
Thanks a lot!
very nice post
This actually answered my problem, thanks!
A simpler way to specify the request’s mimetype is to use $.ajax’s “mimeType” attribute. “contentType” is similar but subtly different (specify both for good measure). So instead of calling $.ajax with a function literal for beforeSend, all you have to do is $.ajax({mimeType: ‘application/json’, contentType: ‘application/json’, …})
very thank you!
I’ve been failed to debug for more than 2 hours until I see this!
It really helps!
I thought jQuery.ajax can realize I was sending a JSON object and it would do something on that. But I’m wrong!
Actually, I need to JSON.stringify it by myself!
Hi, you saved me just some time. Thanks alot!
Hi!
I stumbled until I saw this:
data: {students: JSON.stringify(jsonObjects) }
Thanks a lot!
Hi dude. Nice post – one quick correction though. This line here:
x.overrideMimeType(“application/j-son;charset=UTF-8”);
That’s not the correct MIME type – try this:
x.overrideMimeType(“application/json;charset=UTF-8”);
Only a minor thing, but I thought I’d mention it in case it caused problems in the future.
Cheers!