How to use and configure ajax with jQuery? - Updated Examples

- Andrés Cruz

ES En español

How to use and configure ajax with jQuery? - Updated Examples

AJAX, which stands for Asynchronous JavaScript And XML, is nothing more than a technology that allows creating applications that maintain asynchronous communication with the server; in other words, we can execute functions in parallel with JavaScript using AJAX with jQuery; which turns out to be a simple but at the same time powerful way due to the large number of possibilities it offers and how easy it is to integrate it with other sections of code (since in the end it is JavaScript).

One of the great problems with the current approach when creating web pages is that every time we add dependencies through JavaScript or CSS and even other resources such as images and videos, all these things when consulted through a web page, the browser processes the content of the web little by little from the beginning to the end, when it reaches the loading of a CSS or JavaScript file, the browser stops loading the HTML until it finishes loading the CSS or JavaScript resource in question and then continue with the rest of the load.

AJAX with jQuery has for years been one of the most popular ways to create dynamic web applications without having to reload the entire page. Although the JavaScript ecosystem has evolved a lot since 2013, jQuery AJAX is still relevant, especially in existing projects and legacy applications that still maintain this library as a central part of the stack.

In this article I will explain what AJAX is, how it works with jQuery today, when it is convenient to use it and when not, in addition to showing updated examples and current best practices.

What is AJAX and what is it used for today in web development?

What does AJAX (Asynchronous JavaScript and XML) mean?

AJAX stands for Asynchronous JavaScript and XML and defines a technique that allows JavaScript to communicate with the server asynchronously. This means that we can send and receive data without reloading the page, updating only the necessary parts of the DOM.

Although the name includes "XML", in practice today almost all AJAX works with JSON, which is lighter, easier to read and better integrated with JavaScript.

Why AJAX works mainly with JSON today

In my first projects it was common to receive XML and parse it manually, but over time JSON became the de facto standard. jQuery adapted very well to this, offering methods like $.getJSON() or the dataType: 'json' option in $.ajax().

Differences between classic AJAX and modern requests

Before, AJAX was implemented almost exclusively through XMLHttpRequest. Today there are native alternatives like Fetch API, but AJAX is still the basic concept: asynchronous client-server communication without reloading.

The problem of asynchronous loading in JavaScript

The main problem with all this is that the browser will continue to download content that is part of your website and during this time access to your website by the user would be null or limited in the best of cases and the web is loading in chunks, and all this is time that is directly proportional to the size and number of resources you are loading and all this affects the final experience of your site with the user and also SEO, since nobody wants slow sites...

Is AJAX with jQuery still useful in 2025?

When it makes sense to use jQuery AJAX

AJAX with jQuery is still an excellent option in existing projects where jQuery is already loaded. In these cases, introducing Fetch or Axios just for HTTP requests is not always worth it.

I have often found myself maintaining applications where jQuery is deeply integrated, and there jQuery AJAX is still practical, stable and well supported.

Legacy projects vs new developments

For new projects, my recommendation is clear: Fetch API or modern libraries. However, knowing AJAX with jQuery is still essential if you work with legacy code or old CMS.

AJAX with jQuery versus Fetch API

Fetch is lighter and native, but jQuery AJAX still offers:

  • Normalization between browsers
  • Automatic JSON handling
  • Integrated callbacks and promises

What does AJAX offer us?

With the above, Ajax or asynchronous loading through JavaScript or our case of interest for this entry, jQuery, which offers a simpler way of asynchronous loading than pure JavaScript, comes into play.

Before getting into the subject, let's remember that a long time ago the people at Microsoft invented a technology that would later be known as AJAX which was quite primitive and in the end only allowed the use of one thread in our app (the main UI thread), it made the request and blocked the rest of the app until it finished its execution, something that has evolved a lot to date.

Returning to our case of interest, which is to develop applications that run in parallel; with AJAX we can do a multitude of things to create interactive pages without the need to refresh all the elements of the page:

  • We can obtain data in JSON or XML format although the former has been gaining relevance with respect to the latter.
  • We can obtain a complete page (HTML, CSS, JavaScript) and manipulate it at will from JavaScript.
  • We can receive information asynchronously or synchronously according to our needs.

But... what can we use AJAX for?

  • Imagine that you want to create two lists, one of companies, and another of suppliers where a supplier belongs to a company; without going too far into what the data model would be like; the user must select a company to be able to load a list of suppliers that belong to the company, this loading can be done via AJAX asynchronously without reloading the entire document; we only get the list of suppliers and fill it in the list.
  • Imagine that you want to show an overlay of different pages from the main page according to some option selected by the user; this loading of web pages or sections can be done in a very simple way with AJAX.

With AJAX none of the previous actions require a full page load (as you would have to do if you didn't use AJAX), simply refresh sections of the document; we can even load less necessary resources asynchronously like images.

How AJAX works in jQuery (key concepts)

Asynchronous requests and the main browser thread

An AJAX request does not block the main thread. The browser continues to execute JavaScript while waiting for the server's response, improving the user experience.

Request → response flow without reloading the page

  • The request is sent to the server
  • The server processes the data
  • A response is returned
  • JavaScript updates the DOM

All this happens without refreshing the entire document.

Error handling and HTTP states

A clear advantage of jQuery AJAX is that we can handle HTTP errors (404, 500, etc.) in a centralized way, something that at the time saved me many hard-to-detect bugs.

jQuery.ajax() parameters

jQuery.ajax() handles a large number of parameters that allow you to configure AJAX in many ways according to our needs; but among the most important we can mention the following:

  • url: Contains the URL of the resource to which you want to send the request.
  • async (default: true): By default all requests are configured to be asynchronous; which means that the rest of the JavaScript continues to run regardless of whether it finished processing the request.
  • contentType: Explicitly indicates the type of data to be received from the server.
  • error: Function that is invoked when an error occurs with the request, including server errors and/or statuses: 500, 404, 400 etc.
  • success: Function that is invoked when the request was successfully processed.
  • method or type: GET or POST as the case may be.
  • data

Examples with AJAX and jQuery

In this section we will see a set of examples to demonstrate some of the functionalities of AJAX and exemplify its use along the way; throughout the examples we reference some files through their URL:

  • The file pagina.html contains: <html> <head> <title>My page</title> </head> <body> <h3>My page</h3> </body> </html>
  • The file test.php redirects to pagina.html: <?php readfile('pagina.html');
  • The file test2.php returns a JSON:
<?php
if(isset($_GET['id']))
 echo '{
    "aaData": [
        {
            "id": "132",
            "author_name": "Jean",
            "author_lastname": "Arp",
            "type_name": "Sculpture",
            "zone_name": "Covered Square of the Rectory"
        },
        {
            "id": "133",
            "author_name": "Jean",
            "author_lastname": "Arp",
            "type_name": "Plastic elements",
            "zone_name": "Building of the Faculty of Humanities and Education"
        }
    ]
}';

Example of a simple jQuery.ajax()

The simplest AJAX that I think we can create with jQuery should be something very similar to the following script:

var url="test.php";
$.ajax({
  method : "GET",
  url : url,
  success : function(data) {
  console.log("data",data);
})
.done(function(data) {
  console.log(data);
})
.fail(function(jqXHR, textStatus, error) {
  console.error(error);
});

Or we can even get the page directly:

var url="pagina.html";
$.ajax({
  method : "GET",
  url : url,
  success : function(data) {
  console.log("data",data);
})
.done(function(data) {
  console.log(data);
})
.fail(function(jqXHR, textStatus, error) {
  console.error(error);
});

In both cases, if we look at the developer console, we would see something like this:

data <html>
<head>
<title>My page</title>
</head>
<body>
<h3>My page</h3>
</body>
</html>

We got the content of the HTML page called pagina.html through AJAX.

How the previous exercise works

We just send a request to the resource indicated in the url parameter and it returns a content.

The resource could also be an XML, JSON, a file, etc.

Basic example with JSON

$.ajax({
 url: '/api/data',
 method: 'GET',
 dataType: 'json'
})
.done(function(data) {
 console.log(data);
})
.fail(function(jqXHR, textStatus, error) {
 console.error(error);
});

Example of jQuery.ajax() with parameter passing

If our resource needs to pass one or more parameters, it is necessary to use the data parameter as we will see below:

var url="test2.php";
$.ajax({
method: "GET",
data : {
	id : 5
},
url : url,
success : function(data) {
console.log("data",data);
},
error : function(objXMLHttpRequest) {
console.log("error",objXMLHttpRequest);
}
});

If we look at the developer console, we would see a String like this:

data {
    "aaData": [
        {
            "id": "132",
            "author_name": "Jean",
            "author_lastname": "Arp",
            "type_name": "Sculpture",
            "zone_name": "Covered Square of the Rectory"
        },
        {
            "id": "133",
            "author_name": "Jean",
            "author_lastname": "Arp",
            "type_name": "Plastic elements",
            "zone_name": "Building of the Faculty of Humanities and Education"
        }
    ]
}

And we would have to cast it to an array to be able to manipulate it with a method like:

$.parseJSON(data);

If we want to bring a JSON through AJAX already cast as an array to be able to manipulate it easily:

$.getJSON(url, function( data ) {
  console.log("data",data);
});

Now it returns the data as an array instead of a string.

data
Object {aaData: Array[2]}
aaData: Array[2]
0: Object
author_lastname: "Arp"
id: "132"
author_name: "Jean"
type_name: "Sculpture"
zone_name: "Covered Square of the Rectory"
__proto__: Object
1: Object
author_lastname: "Arp"
id: "133"
author_name: "Jean"
type_name: "Plastic elements"
zone_name: "Building of the Faculty of Humanities and Education"

What is the purpose of passing data in the request?

If we are interested in obtaining a list given one or a series of identifiers, we must use the data parameter indicating the name of the parameter and its value; if there are several, they must be separated by commas (,):

data : {
	id : 5,
	name : 'juan'
},

How to send a form by AJAX?

If we want to send a form by AJAX, we can use the serialize() method provided by jQuery that we have already talked about on another occasion: This is how serialize works in jQuery.

$.ajax({
  method: 'GET',
  dataType: 'json'
  data: $("form").serialize(),
  url : url,
})
.done(function(data) {
  console.log(data);
})
.fail(function(jqXHR, textStatus, error) {
  console.error(error);
});

Ajax methods in jQuery

In case you don't want to use the $.ajax method you can use other methods to save us some lines of JavaScript and that will also allow us to create more concise and descriptive code:

  • $.get Performs a GET request to a provided URL.
  • $.post Performs a POST request to a provided URL.
  • $.getJSON Performs a GET request to a provided URL and expects the returned data to be a JSON; if the returned data is not a JSON, then the script will fail.

As for the arguments you must establish are the following:

  • url The URL to which the request is to be made; its value is mandatory since without the URL there is no resource to generate.
  • data The information that will be sent to the server via GET or POST; its use is optional and can be both an object and a data string: foo=bar&baz=bim).
  • success callback An optional but practically necessary function that if and only if the query was successful and from here we can access the data and handle it.
  • error callback This function is optional and is executed in case the request or query was not successful.
  • data type The type of data expected to be received from the server. Its value is optional.

Simplified AJAX methods in jQuery (shorthand methods)

$.get() and $.post()

Shortcuts for GET and POST requests:

$.get('/data.php', function(data) {
 console.log(data);
});
$.post('/save.php', { name: 'Juan' }, function(response) {
 console.log(response);
});

$.getJSON()

Ideal when we know that the response will be JSON:

$.getJSON('/api/users', function(data) {
 console.log(data);
});

.load()

Loads HTML content directly into an element:

$('#container').load('content.html');

When to use each method

  • .load() → direct HTML
  • $.get() / $.post() → simple requests
  • $.ajax() → total control

Sending data with AJAX and jQuery

Sending data by GET and POST

Data can be sent as JavaScript objects that jQuery automatically serializes.

Sending forms with serialize()

$.ajax({
 method: 'POST',
 url: '/process.php',
 data: $('#form').serialize()
});

This method is still one of the most practical offered by jQuery.

AJAX example with PHP (real case)

$.ajax({
 url: 'text_plain.php',
 type: 'POST',
 data: { name: 'Carlos' },
 success: function(response) {
   console.log(response);
 }
});

In PHP:

echo $_POST['name'];

Synchronous VS Asynchronous with AJAX

An interesting point of AJAX technology is that it is asynchronous; that is, the AJAX is executed without interrupting the rest of the JavaScript code; this can be an inconvenience on some occasions depending on the circumstances or what we want to do:

$.ajax({
  method: "GET",
  url : url,
  success : function(data) {
  console.log("msg1","this will be executed last");
})
.done(function(data) {
  console.log(data);
})
.fail(function(jqXHR, textStatus, error) {
  console.error(error);
});
console.log("msg2","this will be executed before the ajax");

Returns the messages in the following order:

msg2 this will be executed before the ajax msg1 this will be executed last

Since AJAX does not "block" the rest of JavaScript by default, it does not stop the execution of the remaining JavaScript.

If we want it to "block" or stop the execution of JavaScript by default, we must use the async parameter set to false.

$.ajax({
  type : "GET",
  async : false,
  url : url,
  success : function(data) {
  console.log("msg1","this will be executed first");
})
.done(function(data) {
  console.log(data);
})
.fail(function(jqXHR, textStatus, error) {
  console.error(error);
});
console.log("msg2","this will be executed after the ajax");
// msg1 this will be executed first
// msg2 this will be executed after the ajax

Asynchronous vs synchronous AJAX: what you should know today

  • Why async: false is not recommended
    • Synchronous requests block the browser and are discouraged. Today they are considered bad practice.
  • Performance and user experience issues
    • Blocking the main thread generates slow and frustrating interfaces, something that directly impacts UX and SEO.
  • Modern alternatives
    • Promises and async/await offer a clear flow without blocking execution.

Promises, callbacks and async/await with jQuery AJAX

Using .done(), .fail() and .always()

$.ajax('/api/data')
 .done(function(data) {
   console.log(data);
 })
 .fail(function() {
   console.error('Error');
 });

Integration with async/await

async function getData() {
 try {
   const data = await $.getJSON('/api/data');
   console.log(data);
 } catch (e) {
   console.error(e);
 }
}

I have used this pattern a lot to keep code clean without abandoning jQuery.

Functions and parameters of the $.ajax method

The $.ajax method has several configuration options that we can use to adapt the script to our needs; you can consult the complete list at jQuery Ajax; among the main ones we have:

  • async Sets whether the request will be asynchronous or not; by default the value is true; setting the value to false will block the execution of the code until the request is finished; it is ideal to set it to false when we want the returned data to be set in a global variable or something similar.
  • data Sets the data to be sent to the server using the same considerations that we explained previously.
  • jsonp This parameter is very useful and allows you to indicate whether the returned data will be in JSON format or not.
  • type This parameter allows you to set whether the query or request will be via GET (by default) or another such as POST
  • url With this parameter you set the URL of the resource to which the request is to be made.
  • complete It is a function that, like the success one, is the callback function that is executed when the request finished successfully.
  • error This function is executed when an error occurs in the request.

Promise functions: Async/Await to the rescue

So far we have seen how to perform the "traditional" callback where we have a function that is executed in parallel asynchronously, brings data, and we do something with that data like filling a list, a table, etc; but we can take all this to another level, giving a greater level of embedding with our code through promise functions.

Promise functions allow you to manage the flow and handle errors.

Promises also allow, in addition to improving the flow in our app, to "handle" errors or manage them in a simpler way through the well-known try and catch; to use promise functions we must add a couple of reserved words called async and await:

    function getDepartmentsJson(country_id) {
        return $.getJSON("/clients/j_department_by_country_id/"+country_id);
    }
    async function getDepartments() {
        try {
          var departments = await getDepartmentsJson(1);

//          departments = jQuery.parseJSON(departments);
          if(departments.length == 0) throw new Error('No data');

           // do something else
           return departments;
        } catch(e) {
          console.log(e)
        }
    }

As we see in the previous code, our code has a synchronous code structure but it is actually asynchronous, since when it returns the data getDepartmentsJson() the function getDepartments() will be executed and all this thanks to the reserved word async that we put in the function and await that indicates that the function getDepartments() will continue to be executed once the function getDepartmentsJson() finishes executing.

Real use cases of AJAX with jQuery

  • Forms without reloading
  • Dynamic content loading
  • Filters, searches and dependent lists
    • All these scenarios are still ideal for AJAX with jQuery, especially in backoffices and administrative panels.

Advantages and disadvantages of using AJAX with jQuery

  • Advantages
    • Easy to use
    • Compatible with old projects
    • Mature and stable API
  • Disadvantages
    • Dependency on jQuery
    • Not the most modern option for new projects

Common errors when using AJAX with jQuery

  • Not defining dataType correctly
  • Sending badly formatted data
  • Using obsolete practices like async: false

Conclusion: when to use AJAX with jQuery and when not

AJAX with jQuery is not obsolete, but it is not the first choice in new developments either. It is still a very valid tool in existing projects and knowing it allows you to maintain and evolve real applications that are still in production today.

Frequently asked questions about AJAX with jQuery (FAQ)

  • Is AJAX with jQuery obsolete?
    • No, but it is considered more suitable for legacy projects.
  • Is it better to use Fetch API?
    • For new projects, yes.
  • Can AJAX with jQuery be used in modern frameworks?
    • Yes, although it is normally preferred to use native framework tools.

AJAX is a technology that allows you to create applications that maintain asynchronous and parallel communication with the server, although we can also adapt it to work synchronously and we can improve all this with the help of the AJAX functions.

I agree to receive announcements of interest about this Blog.

Andrés Cruz

ES En español