Differences between contentType and dataType in jQuery ajax function
From the documentation:
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: String
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it'll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.
and:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
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 (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
They're essentially the opposite of what you thought they were.
DataType vs ContentType in jquery ajax
dataType:
The type of data that you're expecting back from the server.
contentType:
When sending data to the server, use this content type. Default is
"application/x-www-form-urlencoded; charset=UTF-8", which is fine for
most cases. If you explicitly pass in a content-type to $.ajax(), then
it is always sent to the server (even if no data is sent). The W3C
XMLHttpRequest specification dictates that the charset is always
UTF-8; specifying another charset will not force the browser to change
the encoding.
How to choose the right dataType and contentType value for AJAX request?
As Rory said (as did I, in an answer I wrote then deleted when I saw his comment; he was right to comment instead), a 403 response code probably doesn't mean there's a problem with either dataType
or contentType
. You should look for other reasons the server would refuse to satisfy the request. For instance, as you're posting HTML, perhaps you (or your web host) has some kind of anti-script-injection protection going on. You'll have to track that down, perhaps with your hosting company.
But two things: Some info for completeness, and a potential workaround:
dataType
is the type you expect back from the server. contentType
is the type of data you're sending to the server.
For the request you're sending, leaving off contentType
is correct, because the default jQuery will use is what PHP will expect to see.
You shouldn't have to specify dataType
at all; instead, you should ensure the response carries the correct Content-Type
header. That means ensuring that your server is configured correctly (for static content) and that your PHP code sets the correct header if necessary via header("Content-Type: data/type-here")
The only reason for specifying dataType
is if you don't control the server and you know it sends back the wrong type.
If you need to try to work around it, first ask: What if someone sends me malicious HTML directly, not through my web page? The answer is: You need to be careful with what you do with the HTML. For example: If you are going to store this HTML and then display it (as HTML) to a user, that's a Cross-Site Scripting vulnerability and you have to rigorously sanitize that HTML before doing that.
Do not proceed with any workaround until you've answered that question for yourself.
Okay, so in terms of working around it (once you have robust safeguards in place): You might send JSON rather than a standard form, in hopes that whatever is rejecting the forms won't look at it. To do that, you'd change your ajax call:
var page = {
html: document.querySelector("article").innerHTML,
url: <?php echo "'$current_page'"; ?>
};
$.ajax({
url:'https://example.com/update.php',
type:'post',
data: JSON.stringify(page),
contentType: 'application/json; charset=UTF8',
success:function(data){
window.location.reload();
}
});
Then on the PHP side, you'd read that JSON and parse it (reading code below taken from this answer):
$entityBody = json_decode(stream_get_contents(STDIN));
$content = $entityBody['html'];
$page = $entityBody['url'];
file_put_contents($page, $content, LOCK_EX);
Again: Please do not use this unless you have robust anti-XSS safeguards in place. And again, if you do haev robust anti-XSS safeguards in place, you might be able to just use a normal form by changing your server config.
Jquery AJAX POST without dataType and contentType
If you omit dataType
it won't set an Accept
header and will infer how to parse the response from the Content-Type
response header.
If you don't set a contentType
, it will set a default value for it based on the type of data you pass to data
. Assuming model
is a plain object, that will be application/x-www-form-urlencoded
format and the object will be encoded in that format.
It makes no sense to set contentType
on a GET request: There is no request body to describe the content-type of.
Your code broke when you changed it to POST because you weren't sending JSON and the Content-Type request header became significant (because the data was now in the body).
what difference between data and datatype in jquery?
dataType tells the request what kind of data it expects to receive from the server action . In your case it's json but it could also be xml, html, jsonp, text, or script.
data is the actual form data your ajax request is passing to the server action
See jQuery.ajax for details
What is contentType and dataType and data in jQuery ajax Post?
The contentType referres to the mime content type that specifies the type of content set to the server. This could indentify FORM-Encoded, XML, JSON and a plethora of other content types. It helps the server to determine how to handle the content.
dataType helps JQuery with regards to how to handle the data. if specifying json then the returned data will be evaluated as json and data passed to the success handler will be an object instead of a string
The data property is used for data passed to The server. If you pass in an Object literal. JQuery will pass it either as part of the request body (if type is post) or as part of the query string (if type is get)
dataType vs accepts - Ajax Request
Here is a, hopefully, precise answer:
The accepts
option let you change the Accept
header in the request
When you change this option, the Accept
header in the request will be set to the one(s) specified. Take notice that it is not a string, but an object mapping the MIME type of the accepted responses. Like { text: "text/plain", html: "text/html" }
. The Accept
header can be used by the server to provide the response in the format expected by the request, or fail in case it can't provide the response in one of the formats expected by the request.
A really important thing is that, at least in jQuery 1.11.3 (where I tested), this options seems to not be working, instead I managed to change the header using the headers
option: headers: {Accept : "text/json"}
.
The dataType
option let you pre-process the response
If you define a dataType
, the response of the request will be pre-processed by jQuery before being available to the succes handler. For example:
If
json
is specified, the response is parsed usingjQuery.parseJSON
before being passed, as an object, to the success handler.If
script
is specified,$.ajax()
will execute the JavaScript that is received from the server before passing it on to the success handler as a string.
More examples here, in the "Data Types" section.
In case that dataType
is not set, the Content-Type
of the response will determine what pre-processing should be done to the response. Be aware that changing the dataType
will change the Accept
header too. Usually there is no need to change the Accept
header by yourself.
Example
request.php
<?php
if(strpos($_SERVER["HTTP_ACCEPT"],"text/javascript") === false)
exit("I only provide text/javascript responses");
echo "alert('This is my response!')";
index.html
<button id="send">Send</button>
<div id="response"></div>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(function(){
$("#send").click(function(){
$.ajax({
method: "GET",
url: "request.php",
dataType: "script" // Change this to "text" and you will see the difference
}).done(function(data) {
$("#response").text(data);
});
});
});
</script>
When the dataType
is set to "script"
the Accept
header will include "text/javascript"
so the test on request.php
will pass. It will return "alert('This is my response!')"
and because the dataType
is set to "script"
jQuery will attempt to execute that as javascript and then pass it as plain text to the success handler.
If you change the dataType
to "text"
the Accept
header will NOT include "text/javascript"
so the test on request.php
will fail. It will return "I only provide text/javascript responses"
and because the dataType
is set to "text"
jQuery will pass it as plain text to the success handler.
$.ajax - dataType
contentType
is the HTTP header sent to the server, specifying a particular format.
Example: I'm sending JSON or XMLdataType
is you telling jQuery what kind of response to expect.
Expecting JSON, or XML, or HTML, etc. The default is for jQuery to try and figure it out.
The $.ajax()
documentation has full descriptions of these as well.
In your particular case, the first is asking for the response to be in UTF-8
, the second doesn't care. Also the first is treating the response as a JavaScript object, the second is going to treat it as a string.
So the first would be:
success: function(data) {
// get data, e.g. data.title;
}
The second:
success: function(data) {
alert("Here's lots of data, just a string: " + data);
}
Related Topics
JavaScript Triple Greater Than
Spring Boot Controller - Upload Multipart and JSON to Dto
Does Execcommand Saveas Work in Firefox
How to Import Image (.Svg, .Png ) in a React Component
How to Convert from Hex to Ascii in JavaScript
Get Element's CSS Selector (When It Doesn't Have an Id)
Call JavaScript Function from Url/Address Bar
Chrome Extension: Get Page Variables in Content Script
What Does Variable Declaration with Multiple Comma Separated Values Mean (E.G. Var a = B,C,D;)
Capture the Close Event of Popup Window in JavaScript
[Vue Warn]: Property or Method Is Not Defined on the Instance But Referenced During Render
Get Path Params in React-Router V4
Window.Onload VS. Body.Onload VS. Document.Onready
Dom Refresh on Long Running Function
How to Prevent Moment.Js from Loading Locales with Webpack
Convert JavaScript Array of 2 Element Arrays into Object Key Value Pairs