How can I use JQuery to post JSON data? How can I use JQuery to post JSON data? json json

How can I use JQuery to post JSON data?


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


Base on lonesomeday's answer, I create a 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'        });    }});

Usage:

$.jpost('/form/', { name: 'Jonh' }).then(res => {    console.log(res);});


you can post data using ajax as :

 $.ajax({   url: "url",    type: "POST",   dataType: "json",   contentType: "application/json; charset=utf-8",   data: JSON.stringify({ name: 'value1', email: 'value2' }),   success: function (result) {       // when call is sucessfull    },    error: function (err) {    // check the err for error details    } }); // ajax call closing