AJAX in jQuery

Complete tutorial on AJAX in jQuery. We explain all the alternatives you have to perform Ajax with the jQuery library, from the simplest to the most advanced.

One of the main goals that developers have when we decide to use jQuery is to implement AJAX behaviors to create web applications more similar to desktop applications, which is commonly called RIA or rich user experience.

In jQuery there are various functions to produce AJAX, with various approaches that offer us different solutions and that will be in accordance with different types of needs. In this article I want to offer a basic guide that will serve as an introduction to AJAX in and that will help us to know what the available methods are and in what cases they can be useful.

AJAX jQuery high level and low level

In jQuery there are AJAX methods with various levels of complexity. In the AJAX documentation itself, the creators classify them into “high-level” and “low-level” methods, making a comparison with what high-level and low-level programming languages ​​are.

In programming we say that a language is low level when it is closest to the machine. For example, assembler is low level, because it is programmed with very basic instructions, close to machine language. High-level languages ​​are closer to the language of people and are therefore easier to use. The programming languages ​​that we normally use are high-level and within them there would even be subclassifications such as C, which, despite being high-level, is closer to the machine level than, for example, Javascript.

By saying “low-level functions” it does not mean that they are not very powerful or not very useful, but we must understand it just the opposite. They are closer to what would be the AJAX of the browser, more customizable and more powerful. The high-level ones have a much simpler interface and use, but they are less powerful because they are prepared for a specific use.

The truth is that almost all of jQuery’s functions are high-level, except for jQuery.AJAX() which is low-level, along with other methods that we wouldn’t normally use. It’s good to be familiar with jQuery.AJAX() because it’s a method with which we can perform any kind of AJAX behavior. We will also find it documented or used as $.AJAX() and I call it “almighty AJAX” because with it we can perform any type of use that we may need.

As you should know, $ is a synonym for jQuery, so saying jQuery.AJAX() is the same as $.AJAX().

Now, the truth is that if we know how to choose the high-level functions and configure them well, we will rarely need to use the low-level function $.AJAX(). Although we could also turn the tables and say the opposite, if we know how to use $.AJAX() we would never need to use the high-level functions. Although this is true, sometimes it is convenient to use the high level behaviors because they generate less code and our scripts will be less heavy and also more understandable.

See also  How to tell if a variable is null in Javascript

High-level functions have specializations for performing various types of AJAX connections, and in turn also have different levels of complexity. For example, the .load() function simply loads a text in an HTML element, it is only for that use, we cannot send data to the server by POST and it does not allow the server to give you the response in JSON, but it is extremely powerful , because with a single method call I solve everything that is needed in one go. However, there are other functions that, even though they are simple, have more possibilities, such as jQuery.post() that allows us to configure an AJAX call that sends data to the server through the “post” method.

In the documentation, the methods that I am calling as “high level” we find them classified as “Shorthand Methods” and as it gives us to understand, they are something like quick shortcuts to invoke more specific AJAX functionalities.

AJAX jQuery methods, one by one

.load()

This method is used to load data into a page element. We simply indicate the URL of the file that we want to bring us by AJAX. The method itself updates the HTML of the element on which we are calling .load(). It does not accept more parameters and does not perform more actions than those mentioned.

$(“#item”).load(“page.html”);

If we want to send data by GET to a page, we could use .load() indicating that data “by hand” in the URL of the file we are accessing, but there are better methods to do this.

$(“#item”).load(“page.php?data=222”);

The load() method takes care of everything, making the request to the server and sending the HTML of the response to the container on which we called .load(). If you are interested in knowing more, you can consult the article entitled .

$.get() and $.post()

Two sister methods that do pretty much the same thing: an AJAX connection sending data to the server. The only difference is that $.get() sends the data via GET (in the URL) and $.post() sends it via POST (in the HTTP headers).

We pass a slightly more complex set of parameters to these methods, although only the first one is required.

$.get(“url.php”, { data: “value”, data2: “value2” }, function(response){ $( “#result” ).html( data ); }, “html”);

This would call the URL “url.php” passing through the GET method the data and values ​​indicated in the second parameter. When the response is received, the function indicated in the third parameter will be executed and the data that is expected to be received from the server as a response has the format indicated in the fourth parameter, there being several response formats, such as JSON, script, HTML or XML.

See also  Axios Library: HTTP client for Javascript

You can find . As I said, $.post() is exactly the same, but the data will be sent by jQuery with the POST method, otherwise everything we learn about $.get() can be applied to $.post().

It should be appreciated that .load() is called on a jQuery object, which has one or several page elements, where we want to load content that we bring by AJAX. However, to execute a method like $.post() or $.get() we do it from the $function or jQuery function, so this call is not bound to a given page element. In the function that is executed when the result of the AJAX request is produced, we must select the element or elements where we want to display the results.

As an added benefit, these methods we’re looking at now return an “AJAX object” that we can use to perform new actions that configure our request. For example, we can define things like what to do when the request is executed if an error occurs, etc.

var AJAXObject = $.get( “whatever.php”, function() { //do something when there is an AJAX response }); AJAXObject.done(function() { //do something else when there is a successful response from the request }) AJAXObject.fail(function() { //do something when an error occurs }) AJAXObject.always(function() { / /do something on both error and success });

The functions to execute with this AJAX object are described in greater detail in the article

$.getScript()

This is another “shorthand” method, interesting as it is a shortcut to load a Javascript script and execute it when it has been received correctly. We can configure a sending of data and this method will do it by GET, just like they were sent in $.get(). We can say, in short, that it is used the same as $.get(), but the server’s response is telling it that it will be received in a Javascript script that must be executed as it is.

$.getJSON()

It is another widely used “shorthand method” that receives a response in JSON. It is exactly the same as what was commented with “getScript()”, only that in the response we will receive a Javascript object. The content of the object must be sent to us by the server as a response, always in a JSON that jQuery will internally interpret and convert into a native Javascript object, which we can access to retrieve any of its data.

AJAX Global Events

There is another classification of methods in the jQuery documentation called “Global AJAX Event Handlers”, which are global events that we can assign to any AJAX request that occurs on a page.

Their usefulness is that they are defined only once and affect all AJAX calls that we can make on that page, so we can save the configuration part of various typical behaviors, such as “loading…” messages, in each of the AJAX functions. That is, you define them once and they are valid for all AJAX calls.

See also  Virtual directories in IIS

There are events for when a request occurs, such as when there is an error, response success, etc. These events are added to the jQuery object of the extended document.

$( document ).AJAXError(function() { alert(“An AJAX request failed (don’t ask me which one)”); });

AJAX Almighty $.AJAX()

Everything that we have seen that can be done with the higher-level functions can be implemented with the $.AJAX() function. The power of that method is impressive and allows you to do various specific configurations that we could not do with the shorthand methods, such as setting up a mechanism so that an AJAX request never goes through the browser cache, using crossDoman on a request as JSONP, control various specific server responses such as 404 errors, define a maximum waiting time for an AJAX request, indicate a username and password if we are connecting to a server that requires HTTP authentication, etc.

The study of this method is interesting and will not cost us much when we already know a lot about shortcut methods.

Functions as additional aids

In the “Helper Functions” category of AJAX in jQuery we will find several functions to serialize forms, arrays, objects, etc. It is common for the data that we want to send to the server to be in structures such as objects or arrays, it may even be simply written in form fields. To make our work easier in these common situations, there are methods that allow us, in a simple call, to obtain a string that serializes these arrays or forms objects, which we can send immediately in an HTTP request.

The most typical example is the serialization of a form.

$( “#myform ).serialize();

The response to this serialize() method can be used directly as data that you send to the server when making an AJAX call.

$.post(url, $( “#myform ).serialize(), SuccessFunction);

conclusion

What you have been able to read in this article will give you an overview of everything there is to work with AJAX in jQuery. It is good to have a prior idea of ​​what you are going to find so that from here on you can know what functions may be the ones that interest you to solve your problems.

You can find more information about AJAX in jQuery in the following articles in this . Don’t stop practicing and…

Loading Facebook Comments ...
Loading Disqus Comments ...