How can I use JQuery to post JSON data?

JqueryJsonAjaxHttp Post

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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

Solution 3 - Jquery

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

Solution 4 - Jquery

I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data

$.fn.postJSON = function(url, data) {
    return $.ajax({
            type: 'POST',
            url: url,
            data: data,
            dataType: 'json'
        });

Solution 5 - Jquery

The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.

var Data = {
"name":"jonsa",
"e-mail":"[email protected]",
"phone":1223456789
};


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

Solution 6 - Jquery

Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonasView Question on Stackoverflow
Solution 1 - JquerylonesomedayView Answer on Stackoverflow
Solution 2 - JqueryNinh PhamView Answer on Stackoverflow
Solution 3 - JqueryEr MayankView Answer on Stackoverflow
Solution 4 - JqueryLee HardingView Answer on Stackoverflow
Solution 5 - JqueryDavid ArunView Answer on Stackoverflow
Solution 6 - JqueryloretoparisiView Answer on Stackoverflow