How to Specify Data Type in jQuery $.ajax()
When making asynchronous HTTP requests with jQuery, specifying the
expected data type ensures that the server's response is correctly
parsed and handled by your application. This article explains how to
define the expected response format using the dataType
setting in a $.ajax() configuration, details the supported
data formats, and outlines what occurs when the server response does not
match expectations.
The dataType Setting
To specify the expected return type from the server, add the
dataType property to your $.ajax() settings
object. This property informs jQuery how to treat the incoming data
before passing it to your success callback.
$.ajax({
url: 'https://api.example.com/user/1',
type: 'GET',
dataType: 'json',
success: function(data) {
// data is automatically parsed as a JavaScript object
console.log(data.name);
},
error: function(xhr, status, error) {
console.error('Request failed:', error);
}
});Supported Data Types
jQuery supports several predefined options for the
dataType property:
xml: Parses the response as an XML document, accessible through jQuery XML traversal methods.html: Returns the response as plain text. Any included<script>tags are executed when inserted into the DOM.script: Evaluates the response as JavaScript code and returns it as plain text. Disables caching by default.json: Evaluates the response string as a JSON structure and automatically parses it into a native JavaScript object or array.jsonp: Loads a JSON block using JSONP, adding a callback parameter to the request URL to bypass cross-domain restrictions.text: Returns the raw response as a plain string without transformation.
Automatic Type Detection
If you do not specify a dataType, jQuery inspects the
Content-Type header sent by the web server (MIME type) to
infer the appropriate format:
- A
Content-Typeofapplication/jsonortext/javascriptis automatically parsed as JSON. - A
Content-Typeoftext/xmlorapplication/xmlis parsed as XML. - Other MIME types default to returning raw text or HTML.
Explicitly declaring the dataType is recommended because
it removes ambiguity and guarantees that your application logic receives
data in the expected structure.
Handling Parser Errors
If you declare a dataType and the server returns data
that cannot be parsed into that format (such as an HTML error page when
expecting json), jQuery fails the request and executes the
error callback with a parsererror status.
Ensuring your server sets matching HTTP headers and valid body content
prevents parsing failures.