jQuery and AJAX

Rumman Ansari   Software Engineer   2023-03-23   120 Share
☰ Table of Contents

Table of Content:


  • AJAX Stands for Asynchronous JAvaScript and XML

  • This helps in interchanging data with the server without page reload.

  • Popular websites like Gmail and facebook uses AJAX.

  • With the help of jQuery and AJAX, you can load text, HTML, JSON and XML files from the server directly into the page.

  • There are three important AJAX methods used in jQuery: - load()get(), and post().


load()

This is used to load a text or html file from remote server and directly append them to the page.

Usage:


$(selector).load(URL,data,callback);
  • URL is the mandatory field, which is file location address.

  • data and callback

are optional parameters. They specify what function to be executed after the file load.

  • The callback fuction can have three parameters

    • responseTxt - contains resulting data from server

    • statusTxt - call status: success/fail

    • xhr - XMLHttpRequest object: Eg: 404 error


get()

This method also retrieves data from server just like the load method. While load will directly inject the retrieved data into DOM, get() just retrieves the data and allows user to manipulate it.

  • get() is more generic method while load is restricted to a selector.

  • load can handle only text or html files where as get() does not have that restriction.

Usage:


$.get(URL,callback);
  • URL is the mandatory field, which is file location address.

  • callback is an optional function which will execute after file load. The callback method has 2 optional parameters. They are:

    • data which has the content of the file loaded from the server.

    • status which states whether the load is a success or fail.


post()

This method is also used to send request to server, along with some data.

Syntax:


$.post(URL,data,callback);
  • URL is the mandatory field, which is file location address.

  • data is the information sent along with the request.

  • callback is an optional function which will execute after file load. This too has data and status as parameters.

You can take a look at all the available ajax jQuery methods here:

jQuery-AJAX methods