Page Content

Tutorials

Understanding the AJAX in jQuery With Code Example

AJAX in jQuery

AJAX in jQuery
AJAX in jQuery

AJAX lets web pages connect with servers without refreshing. Twitter and Facebook, where material changes automatically, show how this strategy allows dynamic content updates on the same web page, increasing user engagement.

Why jQuery Simplifies AJAX

Although AJAX in jQuery may be implemented with simple JavaScript by using the XML HttpRequest object, it can be time-consuming and frequently requires intricate handling of browser differences. This was made easier with jQuery, which provides a sophisticated method of handling AJAX interactions for quick web development. Many browser idiosyncrasies are abstracted away by jQuery, which also reduces code size and complexity while offering a standardised method for common operations.

Core Components of AJAX

An AJAX solution usually uses the following technologies at its most basic level:

JavaScript: Used to record user input, decipher server data, and display it on the page.

XMLHttpRequest (XHR): The XMLHttpRequest (XHR) object allows background server requests without interfering with browser processes.

Textual Data: The service provides data in XML, HTML, and JSON formats.

How jQuery Handles AJAX

JQuery handles AJAX in several important ways:

Asynchronous Nature: All AJAX in jQuery requests are asynchronous, thus script execution begins immediately after the HTTP request is sent. By doing this, the browser won’t freeze while retrieving data.

Loading Data on Demand: AJAX is essentially a way to load data into the browser from the server without for a page refresh to be displayed.

Sending Data: Information can be transmitted back to the server from the browser. This is made easier with jQuery, which lets you create query strings from objects.

Data Formats: JSON data, HTML snippets, XML documents, and plain text are just a few of the data forms that jQuery functions can retrieve and analyse.

Callbacks: When an AJAX activity is finished, such as when data is received from the server or an effect is finished, jQuery offers callback functions that run.

Common jQuery AJAX Methods

jQuery provides a number of practical ways to execute AJAX in jQuery queries, including:

load(url, [data], [callback]): HTML is loaded from a remote file and injected into corresponding elements using load(url, [data], [callback]). By providing a selector, this straightforward technique can even load specific sections of an HTML page.

$.get(url, [data], [callback], [returnType]): Loads data from the server using an HTTP GET request.

$.post(url, [data], [callback], [returnType]): Loads a page from the server using an HTTP POST request, typically used for sending data.

$.getJSON(url, [data], [callback]): After receiving JSON data from the server via GET, $.getJSON(url, [data], [callback]) parses it into a JavaScript object.

$.ajax(options): This low-level method uses a given set of options to make an AJAX call. Variants of $.ajax() are frequently mapped to other convenience functions. It has many features, such as authentication, global handler suppression, and caching prevention.

serialize() and serializeArray(): The serialise() and serializeArray() methods encapsulate form input components into query strings or JavaScript data structures, making server transmission easy.

AJAX Events (Global Observers): jQuery provides ways to register callbacks for AJAX events regardless of the code that initiates the call:

  • When an AJAX call begins without other transfers, $(document).Execute ajaxStart(handler).
  • After the last active AJAX request, $(document).ajaxStop(handler) runs.
  • After AJAX requests, $(document).ajaxComplete(handler) is called.
  • Failed AJAX requests return $(document).AjaxError(handler) is invoked.
  • Before sending an AJAX request, $(document).ajaxSend(handler).
  • $(document).ajaxSuccess(handler): Invoked after AJAX request success.

Code Example:

Function load() loads text file content Here, jQuery’s load() method dynamically displays mytext.txt content on a web page without reloading.

<!DOCTYPE html>
<html>
<head>
  <title>AJAX Load Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    #content-area {
      border: 1px solid black;
      padding: 10px;
      width: 300px;
      height: 50px;
      margin-top: 10px;
    }
  </style>
</head>
<body>
<h2>Load Text File using jQuery AJAX</h2>
<button id="load-button">Load Text</button>
<div id="content-area">Content will appear here...</div>
<script>
  $(document).ready(function() {
    $("#load-button").click(function() {
      $("#content-area").load("mytext.txt");
    });
  });
</script>
</body>
</html>

Output:

Load Text File using jQuery AJAX
Load Text
Content will appear here...

Explanation of the code

$(document).ready(function(){ … });: To restrict script access to ungenerated elements, use $(document).ready(function(){… }); to execute jQuery code only once the DOM is fully loaded and ready for manipulation.

$(“#load-button”).click(function(){ … });: $(“#load-button”).If function() is called, click the function. After selecting the button element by ID with a jQuery selector (#load-button), this line adds a click event handler. This method’s code runs when the button is pressed.

$(‘#content-area’).load(‘mytext.txt’);: The main AJAX call is this one. The div element where loaded material is placed is selected by $(‘#content-area’). The AJAX in jQuery method.load(‘mytext.txt’) does an HTTP GET request. Once obtained, the material is immediately added to the #content-area div.

If you have a web server configured for testing AJAX in jQuery examples, clicking “Load Text” will display “This text is from my text file.” inside the black-bordered div without reloading the page when you access this HTML file in a web browser.

Conclusion

Web pages can interact with servers using the potent AJAX (Asynchronous JavaScript and XML) method without requiring a complete page refresh. As demonstrated by contemporary apps like Facebook and Twitter, this makes it possible for material to load and update dynamically, resulting in a more responsive and seamless user experience.

Although the XMLHttpRequest object in raw JavaScript can implement AJAX in jQuery , it can be complicated and inconsistent among browsers. By abstracting these intricacies and providing clear, simple methods like $.load(), $.get(), $.post(), and $.ajax(), jQuery streamlines AJAX. Additionally, it enables sophisticated features like form serialisation and automated callback handling, which speed up and simplify AJAX in jQuery operations.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index