Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use JQuery to post JSON data?

I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:

$.ajax({     type: 'POST',     url: '/form/',     data: {"name":"jonas"},     success: function(data) { alert('data: ' + data); },     contentType: "application/json",     dataType: 'json' }); 

But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.

Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?

like image 527
Jonas Avatar asked Jun 06 '11 16:06

Jonas


People also ask

How pass JSON object in post request ajax?

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 } });

How do you POST a JSON message?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.


1 Answers

You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.

If you pass the data as a string, it won't be serialized:

$.ajax({     type: 'POST',     url: '/form/',     data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),     success: function(data) { alert('data: ' + data); },     contentType: "application/json",     dataType: 'json' }); 
like image 188
lonesomeday Avatar answered Oct 12 '22 23:10

lonesomeday