How can I use jQuery to publish JSON data?

I want to send Json to a web service on the same server. But I do not know how to host Json using jQuery. I 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, data is not accepted as Json on the server. This is the expected data on the server: {"name":"jonas"} , but using jQuery the server gets name=jonas . Or, in other words, this is "urlencoded" data, not Json.

Is there a way to publish data in Json format instead of urlencoded data using jQuery? Or do I need to use ajax manual request?

+55
json jquery post ajax
Jun 06 '11 at 16:50
source share
5 answers

You are 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 will not 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' }); 
+114
Jun 06 2018-11-06T00:
source share

jpost on lonesomeday's answer, I create jpost that wraps certain parameters.

 $.extend({ jpost: function(url, body) { return $.ajax({ type: 'POST', url: url, data: JSON.stringify(body), contentType: "application/json", dataType: 'json' }); } }); 

Using:

 $.jpost('/form/', { name: 'Jonh' }).then(res => { console.log(res); }); 
+4
Dec 20 '16 at 2:00
source share

The main answer worked fine, but I suggest storing the JSON data into a variable before posting it, a little cleaner when submitting a long form or working with big data in general.

 var Data = { "name":"jonsa", "e-mail":"qwerty@gmail.com", "phone":1223456789 }; $.ajax({ type: 'POST', url: '/form/', data: Data, success: function(data) { alert('data: ' + data); }, contentType: "application/json", dataType: 'json' }); 
0
Jun 17 '18 at 23:36
source share

I tried the Ninh Pham solution, but it did not work for me until I changed it - see below. Delete contentType and don't encode json data

 $.fn.postJSON = function(url, data) { return $.ajax({ type: 'POST', url: url, data: data, dataType: 'json' }); 
0
Jun 22 '18 at 10:07
source share

Using Promise and checking if the body object is valid JSON. If the promise reject not received.

 var DoPost = function(url, body) { try { body = JSON.stringify(body); } catch (error) { return reject(error); } return new Promise((resolve, reject) => { $.ajax({ type: 'POST', url: url, data: body, contentType: "application/json", dataType: 'json' }) .done(function(data) { return resolve(data); }) .fail(function(error) { console.error(error); return reject(error); }) .always(function() { // called after done or fail }); }); } 
-3
Feb 21 '17 at 8:41
source share



All Articles