'Ajax calls content type

I have a question regarding to ajax,

I have something like:

ajax({
  type: 'post',
  data: {
    'mode': 'update',
    'data': JSON.stringify(jsonData)
  },
  url: '...',
  dataType: 'JSON', 
  success: function(res) {
    //...
  },
  error: function(res) {
    //...
  }
});

But I do not use contentType, but my request actually contain JSON and one extra info of 'mode', should I add some information here for contentType, I tested my calls, they are working without issues, but I would like to know if there is any issues with this call.

any help would be much appreciated.



Solution 1:[1]

The issue is that your entire data object is not stringified..

try...


var data = {
    mode : 'update',
    data : jsonData
}

$.ajax({
    type: 'post',
    data: JSON.stringify(data),
    url: '...',
    contentType: 'application\json',
    success: function(res){...},
    error: function(res){...}
});

//also might want to try and use the short hand version for post
$.post(url, JSON.stringify(data))
    .done(function(res) { /**/ })
    .fail(function(res) { /**/ });

This solution stringifies the entire data object not just the one property.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1