$.ajax({
url: '',
type: '',
dataType:'',
success: {
}
error: {
}
complete: {
}
});
The $.ajax()
function found in jQuery library is used to perform asynchronous HTTP requests leveraging AJAX.
Let's start by recapping on what AJAX is and how it works.
1. Recap
AJAX stands for Asynchronous JavaScript and XML.
The primary role of Ajax is to handle data asynchronously between a web application and server.
Some typical use cases are:
- Reading data from a web server
- Sending data to a web server
- Updating a web page
As it is asynchronous, there is no need to reload the page. This is because AJAX specifically interacts with servers using the XMLHttpRequest API which establishes an independent channel.
It does this using the API's XMLHttpRequest object. Building a classic AJAX function needs you to initialize this object and pass some arguments
Although you don't need to understand this code, it looks something like this:
function ajaxExample() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
jQuery's $.ajax()
function offers a simplified approach to calling this code.
Let's take a look under the hood.
2. $.ajax() and its parameters
2.1 The example
This article will use a common implementation of AJAX to demonstrate a real-life scenario - search suggestion
.
search suggestion
often uses AJAX to return suggested completions from a database updated in real time for each keystroke a user enters into a search bar.
It's almost immediate and greatly improves user experience. It's also works well when you have a large number of potential inputs too long and impractical for a dropdown list.
Google was one of the first companies to pioneer using AJAX in the mid-2000s.
Moving on, the main parameters of $.ajax()
are:
- url
- type
- data
2.2 url
This is the path of your server-side script that does some processing and returns a result to us in the front-end.
This script will differ depending on which back-end language you have in place. This could be anything from a .NET MVC
controller method to a php
script.
We will use PHP
as an example.
We will have to use the url
parameter to specify our php script
.
Note: we have attached our AJAX call to the change event of a theoretical search bar.
$("#search").change(function() {
$.ajax({
url: 'load_suggestions.php' // The targeted resource
});
});
The PHP
file executed on the server side is called load_suggestions.php
.
We won’t be going into how the script works in this tutorial. But as the name implies, it returns suggestions based on what the user has typed.
This url
is relative and in this case, the file must be in the same directory as the JavaScript file calling the AJAX code, as well as the HTML file to which it is linked.
This code works but doesn't do anything. We also need to specify the type of request.
2.3 type
For the type parameter, we can choose to either send a POST
or GET
request.
POST
if we are sending information to the server
GET
if we are receiving information from the server
We will therefore send a request of type GET
as we are "getting" the suggestions. This goes through the type
parameter.
$("#search").change(function() {
$.ajax({
url: 'load_suggestions.php' // The targeted resource
type: 'GET' // The type of HTTP request.
});
});
Note: The
GET
type is the type that jQuery takes by default. You do not need to specify this parameter when you want to make aGET
request.
2.4 data
This parameter lets us attach JavaScript variables to our HTTP request
which we can then send back to our server-side script.
In our case, we need to send back the current search content in order for our back-end script to work.
__We will add a variable that retrieves the content as it stands in our search bar. __
$("#search").change(function() {
var content = $(this).text() // the users input
$.ajax({
url: 'load_suggestions.php' // The targeted resource
type: 'GET' // The type of HTTP request.
data: 'content=' + content // We pass our variable
});
});
'content=' must correspond to an argument of the same name required in your server script
We can send multiple variables to out server by concatenating them like so:
data: 'var1 =' + value1 + '&var2 =' + value2 + '&var3 =' + value3
2.5 dataType
We can specify the type of data we expect to receive from our server script return value in a GET
request.
This is not strictly necessary and if we don't specify the expected datatype, jQuery will attempt to figure it and usually get it right.
We can receive the following data types :
- "json"
- "xml"
- "html" (HTML as plain text)
- "text" (A text string)
- "script" - executes the response as JavaScript, and returns it as plain text
- "jsonp" - Loads a
JSON
block usingJSONP
. Then adds "?callback=?" to the URL specifying the callback
$("#search").change(function() {
var content = $(this).text() // the users input
$.ajax({
url: 'load_suggestions.php' // The targeted resource
type: 'GET' // The type of HTTP request.
data: 'content=' + content // We pass our variables
dataType: 'html' // The type of data we expect to receive
});
});
I personally don't feel a need to specify a dataType, but know that this argument exists.
3. success, error and complete!
Your HTTP request
is ready, and as long as your server-side script is present and functional, it's going to do some processing and return you a response.
The parameters complete
, success
, error
helps us to handle the response.
3.1 success
The arguments of success are automatically executed if the AJAX call was successful. This is what we use to update our input,
$("#search").change(function() {
var content = $(this).text() // the users input
$.ajax({
url: 'load_suggestions.php' // The targeted resource
type: 'GET' // The type of HTTP request.
data: 'content=' + content // We pass our variables
dataType: 'html' // The type of data to receive, here, from HTML.
success: function(res, status) {
$("#searchDropDownList').val() = res;
}
});
});
res
is the variable containing our server-side response. We use it used to update a theoretical DropDown List attached to our search bar.
The argument status
is a character string automatically generated by jQuery and returns a string describing the status of your request.
3.2 error
If the AJAX call encountered an error on the server side, the error
block will be triggered in the same way as with success
.
$("#search").change(function() {
var content = $(this).text()
$.ajax({
url: 'load_suggestions.php' // The targeted resource
type: 'GET' // The type of HTTP request.
data: 'content=' + content // We pass our variables
dataType: 'html' // The type of data to receive, here, from HTML.
success: function(res, status) {
$("#searchDropDownList').val() = res;
}
error: function(result, status, error) {
console.log( 'something went wrong', status, error);
}
});
});
The function executed by error takes three arguments:
- result
- status
- error
You can name this variables as you like, providing they're in the correct oder!
result
is an XHR
object returned by jQuery.
status
provides information about the server call.
error
is in fact an exception, here you can place a character string to display to your visitor if the AJAX call did not work.
3.3 complete
complete
executes after the AJAX call has been made, regardless of whether it was successful or not.
The parameter will take two arguments, the result object we discussed above and an object of type status. This should be starting to feel familiar. : )
$("#search").change(function() {
var content = $(this).text()
$.ajax({
url: 'load_suggestions.php' // The targeted resource
type: 'GET' // The type of HTTP request.
data: 'content=' + content // We pass our variables
dataType: 'html' // The type of data to receive, here, from HTML.
success: function(res, status) {
$("#searchDropDownList').val() = res;
}
error: function(result, status, error) {
console.log( 'something went wrong', status, error);
}
complete: function (result, status) {
}
});
});
As you can see, the success
, error
and complete
functions process cover all possible outcomes from your AJAX call.
From this complete example, you are now free to liven things up adding functionality to your taste and requirements.
But wait... just before you go..
4. The $.get()
and $.post()
shortcuts
You now know how to create and manage your own simple AJAX calls in jQuery.
There are, however, two handy shortcuts provided by jQuery still to discuss.
Writing an $.ajax()
function and then defining its GET
/ POST
type in the appropriate parameter can be cumbersome.
So, the jQuery team made it easier for developers by creating two shortcuts, $.get()
and $.post()
.
Both work the same way, they implicitly call $.ajax()
by specifying a GET type for $.get()
and a POST type for $.post()
.
And just like standard AJAX, they instantiate the XmlHttpRequest
nitty grittiness in an shorter form.
The syntax looks like this:
$.post(URL,data,callback);
$.get(URL,data,callback,datatype);
Again datatype is not strictly necessary
4.1 $.get()
The $.get()
function is intended to be a shortcut of $.ajax()
with a GET
type.
Here is code implementing the $.get()
function.
$.get(
'target_file.php', // The associated server side script.
'false', // We use false, to say that we are not sending data.
return_function_name, // We only enter the name of the return function.
'text' // Format of the data received. (not necessary)
).done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
function return_function_name (received_text) {
// code to manage the return of the AJAX call.
}
As we can see, the main difference compared to earlier is the speed of writing the AJAX call.
You will also note that we have attached three methods to our call: done
, error
and always
which replaced success
, error
and complete
in jQuery version 1.8. The old syntax still works.
We are attaching these methods on the jqXHR
object, which is the returned by $.get()
.
One last notable thing: the return
function. We have opted to enter its name in $.get()
, and define it below for greater readability.
The return function takes an argument which is automatically generated by the $.get()
response, and it contains the data received from the server.
4.1 $.post()
$.post()
works in the same way as $.get()
.
The only difference is that with POST
, it is mandatory to send variables.
Let's produce an AJAX function that sends an email leveraging the $.post()
function.
$.post(
'send_email.php', // The target file on the server side.
{
subject: $("#subject").val(), // Assuming there is a form on the webpage.
content: $("#content").val()
},
).done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
We can use .done
4.2 Which one should you use - $.ajax(), $.get() or $.post()?
I usually use the two shortcuts to manage my AJAX calls, and I recommend you do the same.
For one simple reason: it is easier to type, understand, and rewrite. This is closer to the message behind jQuery's moto, "Write less, do more."
5. Serialize your forms!
This section is a sort of bonus. I have yet another shortcut up my sleeve.
This shortcut can be used when managing an AJAX call of POST type involving the use of a form.
We going to use jQuery's serialize()
method.
Let's start by looking at an example.
You need to send the variables from an HTML form to a PHP script in AJAX: this is the pretty typical use of the $.ajax()
function.
However, you have a lot of fields and need to concatenate in a string all your variables and their content.
For example:
$.ajax({
/**
* We reuse $.ajax() to illustrate the example
*/
// Let's focus on the data parameters
data: 'value1 =' + var1 + '&value2 =' + var 2 + '&value3 =' + var3,
});
It works, but it's not easy to type.
If we only have a few variables to specify, it is doable, but will quickly become an ordeal if our HTML form is very long.
The solution to this problem is to serialize the form and this is made possible by jQuery's serialize()
method.
serialize()
transforms the fields of a form into a character string containing the variables and their concatenated contents.
An example of serialization()
Firstly, here is an example form.
The goal is to obtain: 'value1 = + var1 + &value2 = + var 2 + &value3 = + var3' in order to send it back to our server via AJAX.
Here's how we can go about automating this:
$("#form").submit(function (e) {// We select the form by its identifier
e.preventDefault (); // Stops the browser from sending the form
var data = $(this).serialize(); // We create a variable that contains the serialized form
$.ajax({
//...
data: data,
//...
});
});
It's just a little tip that saves a lot of time, especially if the form in question is large.
6. Final notes
You know how to make HTTP requests to remote scripts.
But all of this remains very abstract: as we did not explore the server-side processing script for our AJAX calls. That remains for a future article.