207

What is content-type and datatype in a POST request? Suppose I have this:

$.ajax({
    type : "POST",
    url : /v1/user,
    datatype : "application/json",
    contentType: "text/plain",
    success : function() {

    },
    error : function(error) {

    },

Is contentType what we send? So what we send in the example above is JSON and what we receive is plain text? I don't really understand.

Adam Lear
  • 38,111
  • 12
  • 81
  • 101
user2759697
  • 2,103
  • 2
  • 12
  • 5

3 Answers3

354

contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.

dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.

If you're posting something like:

{"name":"John Doe"}

and expecting back:

{"success":true}

Then you should have:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "json",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        alert(result.success); // result is an object which is created from the returned JSON
    },
});

If you're expecting the following:

<div>SUCCESS!!!</div>

Then you should do:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "html",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});

One more - if you want to post:

name=John&age=34

Then don't stringify the data, and do:

var data = {"name":"John", "age": 34}
$.ajax({
    dataType : "html",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
    data : data,
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});
Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • thank you indeed :) what is this "success":true. is it another json file in backend? how this success is made? that is what I really like to know – user2759697 Sep 09 '13 at 15:22
  • 2
    That's just an ordinary object - it's made however the server decides to make it. A web server can send anything it feels like - HTML, text, or in this case, a JSON object with a single property with name "success" and value of true. I can't guess what your API's framework is, but in C# on ASP.NET MVC it would be something as simple as `[HttpPost]public JsonResult user(Person postedPerson) { /* Save postedPerson to DB */ return Json(new { success = true }); }` – Joe Enos Sep 09 '13 at 15:28
  • so we already have
    SUCCESS!!!
    and "success":true files (the files exist on the backend)?
    – user2759697 Sep 09 '13 at 15:29
  • Web applications don't typically return files - they return dynamically generated content. So no actual files exist with that text in it - the text is built in the code, and that text is written directly to the HTTP response by whatever web framework the API is written in. – Joe Enos Sep 09 '13 at 15:31
  • so if i'm specifying dataType in my ajax call, I don't need to specify in the header the accept parameter? Specifically in the below code is the `accept` parameter redundant? `var call = jQuery.ajax({ url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/", type: "GET", dataType: "json", headers: { Accept: "application/json;odata=verbose" } });` – otaku Sep 30 '16 at 06:30
  • @AbhyudayaSrinet If you put `dataType` into the AJAX parameters, then the appropriate headers are done for you. If you need something custom, like yours where you do the `odata=verbose` thing, then you can still define the header yourself. But I believe you still need `dataType: "json"` if you want jQuery to translate the raw response into an object in the `done` or `success` handler. – Joe Enos Sep 30 '16 at 14:03
  • I've used jQuery for close to 10 years now and still get dataType and contentType mixed up if I'm not pulling from an example in my current project. Can someone link a good boilerplate GIST for basic AJAX interactions? – Joseph Coco Apr 21 '17 at 21:38
  • It confuses me every time I get back using jQuery, just can't remember it. Different wording perhaps? `dataTypeSend` and `dataTypeReceive` would be easier to remember. – Legends Feb 03 '18 at 22:31
  • @Legends They do use different value sets - `contentType` sets the actual value of the `Content-Type` HTTP header on the request, while `dataType` is more general - `json` or `text` or `html` or whatever, which doesn't have any relation to the `Content-Type` of the response. Like most things, I had to look up the syntax the first several times I used it, until I did it a bunch of times, then it was fine. – Joe Enos Feb 05 '18 at 16:08
  • Yes, but if I don't use it a longer time, then I forget it. Different wording would help, at least in my case :D ;-). Both deal with types of data. – Legends Feb 05 '18 at 21:16
  • Out of interest why do you think the jQuery folks would use the terms contentType and dataType, why not just call it sendDataType and recieveDataType to make it very clear and concise? – Jacques Feb 22 '18 at 12:39
  • @Jacques `contentType` is the actual `Content-Type` (the HTTP header) of the request. `dataType` is how the return data is expected to be represented, regardless of the content type of the response. I've never sent anything in the post other than straight form-fields or JSON, but I suppose you could send just about anything, like XML, plain text, encoding other than UTF-8, or other content types, which makes the `contentType` useful as a straight passthrough. But jQuery only knows how to handle a few distinct types of response data, which is why those are simple like `html` and `json`. – Joe Enos Feb 22 '18 at 14:28
  • 1
    @Jacques I suppose they could have done `requestContentType` and `responseDataType`, but in reality, once you've done it a couple times, and you understand the API, you won't be confused enough to make the extra typing worthwhile. – Joe Enos Feb 22 '18 at 14:29
  • Thanks Joe, it makes sense. I asked the question because I know I have seen it asked many times before and taking a very quick look at SO alone for questions related to this subject there are a number of related questions with just short of 400 000 views. But, you are right though, once you get used to it you probably won't need to think about it so much. – Jacques Feb 22 '18 at 15:10
  • One doubt, GET method doesn't have request body, it passes parameters as Query Strings, then how in your first example you are posting `Json` type to server, Can `Json` be passed as Query string ? – Shaiju T Jan 18 '19 at 16:45
  • 1
    @stom The question and my answer were specific to POST, but if I recall, if you pass an ordinary simple object as the data on a GET, it'll turn that into a query string with key-value pairs. Not sure what would happen if you had a complex object with nested values - but it shouldn't be difficult to try that if you're curious. I would never do that in real life though - very rarely do I ever use AJAX on a GET anyway. – Joe Enos Jan 19 '19 at 18:21
  • Probably very old, but `JSON.stringify(data)` stringify saved my live... thanks again. – Cyber Jan 17 '20 at 18:45
37

From the jQuery documentation - http://api.jquery.com/jQuery.ajax/

contentType When sending data to the server, use this content type.

dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response

"text": A plain text string.

So you want contentType to be application/json and dataType to be text:

$.ajax({
    type : "POST",
    url : /v1/user,
    dataType : "text",
    contentType: "application/json",
    data : dataAttribute,
    success : function() {

    },
    error : function(error) {

    }
});
Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
  • thanks indeed and what is this application in application/json. is it a path? – user2759697 Sep 09 '13 at 15:11
  • 1
    @user2759697 That's just part of the defined MIME type for JSON. See this question - http://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type – Richard Dalton Sep 09 '13 at 15:13
3

See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.

They are both used in the request to the server so the server knows what kind of data to receive/send.

Jono
  • 3,949
  • 4
  • 28
  • 48