What is ajax
AJAX stands for Asynchronous Javascript and XML and is used to fetch or send data from or to a server. AJAX is used for creating fast and dynamic web pages since it allows fetching data in the background after or during the page is loaded.
In traditional applications, web pages were loaded completely. This means that entire page data will be fetched from the server and then rendered on the browser. If the user clicks a link, then the same would happen with the next page.
But, with the use of AJAX, HTML, CSS and Javascript, now, complete page is not loaded. Some portion or a basic skeleton of the page is loaded at first and rest of the data is being fetched in the background.
Also, AJAX allows only the required parts of a web page to be updated and not the entire page to be reloaded again. Thus, now you can refresh only a single table with new contents.
Typical examples are
A. Sports sites which show updated scores in real time. The updated scores are being continuously fetched by AJAX and Javascript is used to replace the old score.
B. Another example is a stock market website which shows latest prices of stocks changing every second. This is also possible with AJAX and other technologies.
jQuery ajax
jQuery provides the support for AJAX using its ajax()
function. This means that if you are using jQuery in your application, then you can
- Fetch data in the background during or after the page is loaded.
- Send and save data to the back end server on a button click.
- Perform health checks with the back end server in the background.
- Dynamically update only required parts of the web page.
jQuery ajax()
function allows you to make HTTP GET, POST, PUT and DELETE requests and this tutorial will teach you how to do that.
jQuery ajax function syntax
Syntax for using ajax function is
$.ajax(url, [settings])
where url is the URL to which the request will be sent
settings is the configuration for customizing the request. It is a JSON object which specifies options such as type of request, data to send to the sever, type of data being sent, type of expected response from the server and many more. All options will be discussed later.
Providing request settings is not mandatory. You can also
jQuery ajax GET example
jQuery ajax call for GET request is used for fetching data from the server. Below is the code snippet for sending a simple jQuery ajax GET request.
This code uses a dummy public URL which can accept HTTP GET, POST, PUT and DELETE requests so that you can use the code given here directly without an effort to set up a web server.
$.ajax('https://jsonplaceholder.typicode.com/posts/1', {
type: 'GET',
dataType: 'json'
complete: function(response) {
console.log(response);
}
});
Above code will send an AJAX request to the given URL. It uses a settings object with 3 parameters which specify that the request is a GET request with the type of response as JSON and a function to execute when the request completes.
Response from the server is received as an argument to the success
callback function from ajax options.
You can also write URL as a part of settings object using url
option in which case you do not need to write it as a separate argument as shown below.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1',
type: 'GET',
dataType: 'json'
complete: function(response) {
console.log(response);
}
});
Note the url
key added to the settings object. When any of the above calls are executed, then you get below response printed at the browser console.
{userId: 1, id: 1, title: “sunt aut facere repellat provident occaecati excepturi optio reprehenderit”, body: “quia et suscipit suscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto”}
Ajax settings or options
jQuery ajax()
function accepts configurable settings. This is a json object with key-value pairs. Values are either string, json objects or functions which are automatically called by jQuery, also called callback functions.
Below table describes the most commonly used options and their meanings. For simple requirements, these options will serve the purpose and you would not need other advanced options.
Option | Description |
---|---|
url |
URL at which the request should be sent. |
type |
Type of request. Example values are GET, POST, PUT, DELETE, HEAD(case insensitive). Default is ‘GET’. |
data |
Data to be sent to the server. It may be a json object, string or an array. If the request is GET, then these values are appended to the URL. |
dataType |
Expected type of response from the server. Example, xml , script , html , json , jsonp , text .Use this value as per the type of response else there may be unexpected error since it tries to convert the response to the specified type. |
contentType |
Type of the content sent to the server. Default is "application/x-www-url-form-encoded" and will be suitable for most cases. |
headers |
A json object of key-value pairs with key as the header name and value as header value sent to the server. Default is {} |
statusCode |
An object of key-value pairs with key as the status code and value as a function to execute when the response code of the response matches it. Example,statusCode: { 404: function() { console.log('URL not found'); } } |
success |
Function which is called when the ajax request succeeds. This method will not be called if there is any error in the request. It accepts 3 arguments data: data sent from the server converted to the format given in dataType option. status: Text status. In this case, its value will be 'success' .jqXHR: jqXHR object. This object is a superset of browser’s XMLHttpRequest object and contains different properties and functions.Note that it is not necessary to provide all the 3 arguments. But they will be populated in the same order as listed. |
error |
Function which is called when the ajax request ends in an error. This method will only be called if there is any error in the request. It accepts 3 arguments jqXHR: jqXHR object. This object contains different properties and functions.status: Text status. In this case, its value will be 'error' .error: Error thrown by the server, if any. Note that it is not necessary to provide all the 3 arguments. But they will be populated in the same order as listed. |
complete |
Function called after the request completes. It accepts following 2 arguments jqXHR: jqXHR object.status: String containing the status of request. Probable values are success , notmodified , nocontent , error , timeout , abort and parsererror. This method will be called after the success or error callbacks, if written. |
timeout |
Max time in which the server should respond the request in milliseconds. |
beforeSend |
Function that is invoked just before sending the request. A false value returns from this function will cancel the request.Thus, you can perform some checks before sending the request such as presence of a cookie and prevent the request if it exists. |
async |
True (default) or false value. If this value is false , then this call will block further execution till it completes.Since this is not the desired behavior of ajax, this option is deprecated since jQuery 1.8. |
method |
Same as type . Use this option for jQuery versions 1.9 and above. |
jQuery ajax POST example
POST request is used for creating a new entity on the server. jQuery’s ajax()
function supports making POST requests. The value of type option for this type of request is POST along with some data sent to the server in the data
option. Example,
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'POST',
dataType: 'json',
data: {
title:'codippa',
type:'website',
id:1
},
complete: function(response) {
console.log(response);
}
});
Notice the data
option is a json object containing the data sent to the server. The server returns the same data that is sent to it and the same is received as an argument to the function defined in success
option.
jQuery ajax post call can be used to submit an HTML form data directly to the server so that it can be saved to the database.
jQuery ajax PUT example
PUT requests are used for updating data on the server. Example,
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1',
type: 'PUT',
dataType: 'json',
data: {
title: 'codippa.com',
type: 'website',
id: 1
},
complete: function(response) {
console.log(response);
}
});
Notice the value of type
option and the URL which points to a single record that needs to be updated.
jQuery DELETE example
DELETE method is for deleting a record from the server. It may or may not be required to send any data in this request depending upon the handler for this URL on the server. Example,
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1',
type: 'DELETE',
complete: function(response) {
console.log(response);
}
});
Above ajax request will delete the record with id 1 from the server.
jQuery ajax updations
As we saw above, $.ajax()
function provides callback methods which are executed automatically for a request based on its status such as success
, error
and complete
.
Starting jQuery 1.5, $.ajax()
returns an object of type jqXHR
which contains functions that can be executed after the request completes. These functions are:
1. done: This function is similar to success
callback function. It receives 3 arguments:
data: response sent from the server,
status: the text status of the request. For this request, it will be success and
jqXHR: jqXHR object itself.
2. fail: This function is similar to error
callback function. It receives 3 arguments:
jqXHR: jqXHR object itself.
status: the text status of the request. For this request, it will be error and
error: error thrown by the server.
3. always: This function is similar to complete
callback function and was added in jQuery 1.6. It receives 3 arguments:
data OR jqXHR: If the request is a success, then this argument is similar to the first argument of done
function, that is, data sent by the server else it is similar to the first argument of error
function, which is, jqXHR object.
status: the text status of the request. If the request is successful, its value will be success else it will be error. and
jqXHR OR error: This will be similar to the third argument of done or error function depending on the result of request.
For successful request, this argument will be the jqXHR object and if there is some error, then it will be the error thrown by the server.
Example of the above functions is
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'POST',
dataType: 'json',
data: {
title:'codippa',
type:'website',
id:1
},
}).
done(function(data, status, jqXHR){
console.log(status);
}),
fail(function(jqXHR, status, error){
console.log(error);
}),
always(function(dataOrjqXHR, status, errorOrjqXHR){
console.log(status);
});
With these functions, there is no need to use success
, error
or complete
callback functions.
Remember that the names of arguments in all the above functions are just an example. It is not mandatory to use the same names.
Hope this post helped you to learn the concept of ajax function in jQuery. Do not forget the to click the clap button below.