Updated July 1, 2023
Overview of jQuery Ajax Methods
Let us first distribute the words jQuery and Ajax and know the literal meaning of each of these. JQuery is a javascript library that is very lightweight, and it only says us to write less and do more. But before coming to jQuery, you must know the basics of html, CSS, and javascript. The main task of jQuery is to make the developer task easy to render Javascript on the browser easily and in very little time. In easy words, we can say that jQuery turns a heavy line of javascript code into a single line of code using jQuery methods. jQuery also simplifies the complicated javascript code, dom-manipulation, and Ajax call.
Features of jQuery Ajax Methods
Here are the following features:
- HTML event methods
- CSS manipulation
- DOM/HTML manipulation
- AJAX
- Effects and animations
- Utilities
I think you have a lot of basic knowledge of jQuery, so let’s come to the meaning of AJAX. Ajax stands for asynchronous javascript and XML( extensive markup language ). Ajax simplifies and provides the easiest way to create dynamic web pages. Ajax enables us to exchange data without refreshing the web page. It means that we can exchange a small amount of data with the server without refreshing the page; in other words, we can say Ajax updates the webpage without reloading the page. In classic web pages, they need to fill the whole page to exchange data with the server or update the web page. Let us discuss, in short, how it works.
So basically, whenever an event occurs, the browser creates an XMLHttpRequest object and sends an HttpRequest to the server. Then the server processes this HTTPRequest creates a response, and sends data back to the browser. Now, the browser process the returned data using javascript and update the page content.
So after understanding both of these terms, it’s time to discuss the topic. So what is jQuery Ajax? jQuery provides many methods that help in Ajax server-side updating of web pages. The syntax for jQuery ajax is jQuery.ajax( url [, settings ]), where the URL is a string from which a request is sent. The setting is the type of plain object. The jQuery ajax methods provide valuable, resourceful functionality to the ajax in jQuery. An Ajax has an url and an option like this :
$.ajax(url);
$.ajax(url,[options]);
Here url is a type of string through which we can send and receive data, and options are ajax request configuration. There are many options available in jQuery ajax.
Let’s discuss some of them.
- Accepts: It tells the server what kind of response in return it would accept.
- Async: To send the data synchronously, you need to set it to false because, by default, the data is sent or received asynchronously.
- BeforeSend: It means that before sending an AJAX request, you need to execute a callback function.
- Cache: By default, it is true. A browser cache shows through Boolean.
- Complete: You must execute a callback function when a request is finished.
- contentType: Default contentType is “application/x-www-form-urlencoded; charset=UTF-8”.
- crossDomain: A boolean value represents whether the processed request is the cross-domain.
- Data: The data is in the form of an array, string, or object that needs to be sent to the server.
- dataType: The type of data you expect the server to return.
- Error: It means that a callback function needs to be executed when the request fails.
- Global: By default, it is true. It gives a Boolean response of whether to activate a global request.
- Headers: An object needs to be sent along with the request.
- ifModified: If the request has changed from the last updated request, then only the response is valid.
- isLocal: It allows the current or present development environment to be recognized as
- Jsonp: In a jsonp request, it overrides the callback function.
- jsonpCallback: It is a type of string that contains a jsonprequest in the name of the callback function.
- mimeType: It contains a mime type to override xmlhttprequest.
- password: It is used for making an HTTP authentication request.
- processData: By default, it is true; it only gives the Boolean response whether data assigned to the data option should be converted to a query string.
- statusCode: A numeric http request code that responds according to the corresponding code response.
- Success: If the httprequest has succeeded, then only the callback function should be executed.
- Timeout: It is the timeout value of the response in milliseconds.
- Type: It is the type of HTTP requests like GET, PUT, or POST. By default, it is GET.
- url: It is the string containing url where data must be sent.
- Username: It is also used in XMLHTTP authentication requests.
- Xhr: It is the callback function to create the xmlhttprequest object.
- xhrFields: It is a pair set value of fieldName-fieldValue.
Methods of jQuery Ajax
Now let’s discuss some jQuery ajax methods with their syntax & examples. Below are the mentioned jQuery methods.
1. jQuery.get( url, [data], [callback], [type] )
This method helps us load data from the server using the GET HTTP Request. This method also returns an XMLHttpRequest object.
- url – The string containing url through which data is sent.
- Data –This optional parameter contains the key and value pair sent to the server.
- Callback is also an optional parameter that means a function will be executed when the ajax request succeeds.
- Type is an optional parameter that returns data type after callback functions such as html, xml, json, text, and jsonp.
Example:
$(document).ready(function() {
$("#driver2").click(function(event){
$.get(
"result.php",
{ name: "Zara2" },
function(data) {
$('#stage2').html(data);
}
);
});
});
2. jQuery.getJSON( url, [data], [callback] )
This method loads json data from the server through the GET HTTP Request.
- url – The string containing url through which data is sent.
- Data – This optional parameter contains the key and value pair sent to the server.
Example:
$(document).ready(function() {
$("#driver2").click(function(event){
$.getJSON('result.json', function(jd) {
$('#stage2').html('<p> Name: ' + jd.name + '</p>');
$('#stage2').append('<p>Age : ' + jd.age+ '</p>');
$('#stage2').append('<p> Sex: ' + jd.sex+ '</p>');
});
});
});
3. jQuery.getScript( url, [callback] )
This method loads and executes the javascript file through HTTP GET Request.
- url – The string that contains the URL through which the data is sent.
Example:
$(document).ready(function() {
$("#driver2").click(function(event){
$.getScript('result.js', function(jd) {
// Call custom function defined in script
CheckJS();
});
});
});
4. jQuery.post( url, [data], [callback], [type] )
This method loads a web page using HTTP POST Request.
- url – The string that contains the URL through which the data is sent.
- Data –This optional parameter contains the key and value pair sent to the server.
- Type – It is also an optional parameter that returns a type of data after callback function such as html, xml, json, text, jsonp.
Example:
$(document).ready(function() {
$("#driver2").click(function(event){
$.post(
"result.php",
{ name: "Zara" },
function(data) {
$('#stage2').html(data);
}
);
});
});
5. load( url, data, callback)
This method loads the data or object from the server and replaces the returned html after the success request to the matched element.
- url – It is the string that contains url through which data is sent.
- Data – This optional parameter contains the key and value pair sent to the server.
Example:
$(document).ready(function() {
$("#drive2r").click(function(event){
$('#stage2').load('result.html');
});
});
6. serialize( )
This method helps to serialize a set of input elements into a set of the data array. There is no parameter in this jQuery ajax method. For example-
$(document).ready(function() {
$("#driver2").click(function(event){
$.post(
"/jquery/serialize.php",
$("#testform1").serialize(),
function(data) {
$('#stage2').html(data);
}
);
var str = $("#testform1").serialize();
$("#stage3").text(str);
});
});
7. serializeArray( )
This method functions the same as serialize method; the only difference is that it returns json data structure. This method also does not have any parameters. For example-
$(document).ready(function() {
$("#driver2").click(function(event){
$.post(
"/jquery/serialize.php",
$("#testform1").serializeArray(),
function(data) {
$('#stage2').html(data);
}
);
var fields = $("#testform1").serializeArray();
$("#stage3").empty();
jQuery.each(fields, function(i, field){
$("#stage3").append(field.value + " ");
});
});
});
8. ajaxComplete( callback )
This method binds a function to execute when the callback function succeeds.
Example :
$(document).ready(function() {
$("#driver2").click(function(event){
$('#stage2').load('result.html');
});
$(document).ajaxComplete(function(event, request, settings){
$("#stage3").html("<h1>Request Complete.</h1>");
});
});
9. ajaxStart( callback )
This method attaches a function to execute before the AJAX request starts.
Example:
$(document).ready(function() {
/* Global variable */
var count = 2;
$("#driver2").click(function(event){
$('#stage2').load('result.html');
});
/* Gets called when the request starts */
$(document).ajaxStart(function(){
count++;
$("#stage3").html("<h1>Starts, Count :" + count + "</h1>");
});
/* Gets called when request complete */
$(document).ajaxComplete(function(event,request,set){
count++;
$("#stage4").html("<h1>Completes,Count:" + count + "</h1>");
});
});
10. ajaxError( callback)
This method attaches a function that executes whenever the AJAX request fails. This is also a type of ajax event.
Example:
$(document).ready(function() {
$("#driver2").click(function(event){
/* Assume result.text does not exist. */
$('#stage12').load('/jquery/result.text');
});
$(document).ajaxError(function(event, request, settings ){
$("#stage22").html("<h1>Error in front page.</h1>");
});
});
11. ajaxSend( callback)
This method calls a function immediately after sending the AJAX request. This is also an ajax event.
Example:
$(document).ready(function() {
var count = 0;
$("#drive2r").click(function(event){
$('#stage1').load('result.html');
});
$(document).ajaxStart(function(){
count++;
$("#stage12").html("<h1>Starts, Count :" + count + "</h1>");
});
$(document).ajaxSend(function(evt, req, set){
count++;
$("#stage23").html("<h1>Sends, Count :" + count + "</h1>");
$("#stage23").append("<h1>URL :" + set.url + "</h1>");
});
$(document).ajaxComplete(function(event,request,settings){
count++;
$("#stage33").html("<h1>Completes, Count :" + count + "</h1>");
});
});
12. ajaxStop( callback)
This method attaches a function executed just after the ajax request has ended.
Example:
$(document).ready(function() {
var count = 0;
$("#driver2").click(function(event){
$('#stage1').load('result.html');
});
$(document).ajaxStart(function(){
count++;
$("#stage12").html("<h1>Starts, Count :" + count + "</h1>");
});
$(document).ajaxSend(function(evt, req, set){
count++;
$("#stage22").html("<h1>Sends, Count :" + count + "</h1>");
$("#stage22").append("<h1>URL :" + set.url + "</h1>");
});
$(document).ajaxComplete(function(event,request,settings){
count++;
$("#stage3").html("<h1>Completes, Count :" + count + "</h1>");
});
$(document).ajaxStop(function(event,request,settings){
count++;
$("#stage44").html("<h1>Stops, Count :" + count + "</h1>");
});
});
13. ajaxSuccess( callback)
This method invokes a function immediately after the successful completion of the AJAX request.
Example:
$(document).ready(function() {
var count = 2;
$("#driver2").click(function(event){
$('#stage2').load('result.html');
});
$(document).ajaxStart(function(){
count++;
$("#stage12").html("<h1>Starts, Count :" + count + "</h1>");
});
$(document).ajaxSend(function(evt, req, set){
count++;
$("#stage22").html("<h1>Sends, Count :" + count + "</h1>");
$("#stage22").append("<h1>URL :" + set.url + "</h1>");
});
$(document).ajaxComplete(function(event,request,settings){
count++;
$("#stage32").html("<h1>Completes,Count:" + count + "</h1>");
});
$(document).ajaxStop(function(event,request,settings){
count++;
$("#stage42").html("<h1>Stops, Count :" + count + "</h1>");
});
$(document).ajaxSuccess(function(event,request,settings){
count++;
$("#stage52").html("<h1>Success,Count :" + count + "</h1>");
});
});
Now let’s discuss the importance of jQuery ajax methods, listed below:
- This feature has compatibility with various browsers and supports almost all of them.
- It provides a straightforward method to refresh a web page’s content without reloading it.
- It can also send both POST and GET Requests and load HTML, JSON, XML, or scripts.
Recommended Articles
We hope that this EDUCBA information on “jQuery Ajax Methods” was beneficial to you. You can view EDUCBA’s recommended articles for more information.