85

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?

Jonas
  • 121,568
  • 97
  • 310
  • 388

6 Answers6

167

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'
});
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • 5
    Please use $.post for that instead of $.ajax. – user3746259 Jul 25 '15 at 20:27
  • 18
    @user3746259 Why would you want to use `$.post` for that? It is (a) only a wrapper for `$.ajax` and (b) unable to do what is required here (i.e. the `contentType` property). – lonesomeday Jul 27 '15 at 17:15
  • 5
    Until, you know, jQuery 3, that is, which is still in the future *now*, never mind when this answer was written *over four years ago*. – lonesomeday Jul 27 '15 at 17:17
  • @lonesomeday Thanks. I had the same problem and after converting the object to string, it worked. – Dame Lyngdoh Jun 12 '17 at 19:59
  • @lonesomeday i had to use your approach even in 3.2 to force contentType to json. *shrug* – Lo-Tan Nov 10 '17 at 19:20
  • You should probably add `error: function(jqXhr, status, error) { alert(status + ': ' + error);` to the above solution in order to report any issues back to the browser. – lafual Aug 27 '19 at 04:54
  • @lafual That's a very bad idea. If you have to log it somewhere, use `console.log`, but browser development tools will give you more useful information without doing anything. The `error` callback should only be used to enable your program to respond to an error. – lonesomeday Aug 27 '19 at 07:13
  • It was only an example to show that there could be an error and how it could be displayed. If a user runs the post via an html page, how would you inform them of the issue? For sure, when developing, you can use console.log, but for an end user? – lafual Aug 27 '19 at 07:49
  • @lafual That depends entirely what the request was doing. Sometimes it won't be necessary to inform the user. It will, I think, almost *never* be useful to give them the raw Ajax error. – lonesomeday Aug 27 '19 at 08:33
13

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);
});
ninhjs.dev
  • 7,203
  • 1
  • 49
  • 35
1

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
Er Mayank
  • 1,017
  • 2
  • 16
  • 39
-1

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'
        });
Lee Harding
  • 17
  • 1
  • 3
-2

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":"qwerty@gmail.com",
"phone":1223456789
};


$.ajax({
    type: 'POST',
    url: '/form/',
    data: Data,
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});
David Arun
  • 45
  • 1
  • 9
-3

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
            });
    });
}
loretoparisi
  • 15,724
  • 11
  • 102
  • 146