Open In App

What is the use of jQuery.ajax() method ?

Last Updated : 21 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

AJAX is an important concept that must not be missed if you are learning front-end web development. It is an important aspect of the JavaScript programming language that allows the website to make requests to the server and exchange data without disturbing the page, that is without having it reload.

JQuery makes using AJAX easier through its ajax() method. There are other methods for this purpose, but the ajax() method is a general-purpose method that carries out all sorts of functionalities related to AJAX, alone and efficiently. It also makes the process of development easier as the developer can stay consistent since he has to use the same method for all AJAX work.

When you are using the ajax() method, you make a request to a URL, and receive some data from it. You can also send some data to that URL, and you will get a response to confirm the success or error. All of this happens without reloading the page. The AJAX runs in the background without disturbing any currently running script or process, asynchronously. This makes the exchange of data between URLs very fast and efficient, as reloading the page for every single type of request would make it hard for the user to have the best experience as it will slow down the web application. 

Its use is simple, we pass an object to it, which has keys that have a special meaning for it. For example, the url key’s value is accessed and used as the URL to which the request is to be sent. The method key specifies the type of the request being made, i.e., whether it is GET, POST, PUT, PATCH, DELETE, etc., which simply tell the server what kind of operations needs to be done with this URL, and data sent in it. The success key is the most important one, where we define the function, which reads the response.

Example: We will demonstrate an example of its use. Keep an eye on the tab of browser. Notice that it will not reload at all.

Step 1: Set Up Project Folder

Create an empty folder in VS Code and create an HTML file inside it. You can use the following dummy code, to begin with. We are going to use JSON placeholder, which is a service that provides us with fake API to test our data fetching and writing requests. We will be using it to read and write posts using the ajax() method of the jQuery library.

In order to work with AJAX, we are going to need a web server, for this purpose, we will use NodeJS and its third-party package hosted on NPM, liver-server. You can use some other web server, such as Apache as well. 

Open the command line, and type the following command in it.

npm install live-server -g

The above command will install the third part package liver-server that gives us a web server through which we can use AJAX. The -g flag will install it as a global dependency, i.e., it will accessible from anywhere in our computer, and not just this folder. To start the server, type this command:

live-server

Make sure you are in your project folder in your command line when you are typing the above command. This will run your application on port 8080 by default. You can specify a different port by adding a flag to the above command. For example, if you want to use port 3000, use the flag like this:

liver-server --port=3000

In the browser’s URL box, you will see your application, in this case, an HTML page, at the URL: localhost:8080 if you did not specify the port to use in the command, if you did, replace 8080 with the port you specified.

Step 2: Making a GET request

  • We want to see a post whenever we click our button, thus we listen for the click event on that button. We select it using its id and call the click() method on it. This takes a callback as an argument, which is run only when this button is clicked. In this callback, first, we generate a random number between 0 and 100. Since there is no post 0 on JSON Placeholder, we generate the number again if the number we got turns out to be 0.
  • Then, we make a request to the URL of the JSON Placeholder to fetch a post. We simply an object to the $.ajax() method, with three fields, url key to tell it where to go, a method key to tell it the type of request, here, GET, since we are only reading data, and the third key is the success key, which is the function that runs when the request was a success. This function gets a parameter from the $.ajax() method, which is the resulting data. Here, this data is an object. 
  • We access the userId, title and body keys, wrap them in an h5, h1, p tag and an hr tag, and append them to the main tag by calling the append(”) method on the main selector.

Now, go to the browser, and click on the button multiple times. You will get a new post for every click you made, but the page will never reload. Huge and complex web applications keep their services fast and user experience as smooth as possible because of AJAX. Using AJAX in vanilla JavaScript might be a little tough for some people, but is extremely easy in JQuery. 

NOTE: Instead of using the success key, you can chain the done() method to the ajax() method and define that success function inside it.

Filename: index.html

HTML




<!DOCTYPE html>
<html lang="en">
  
<body>
    <header>
        <h1 style="color:green">GeeksforGeeks</h1>
        <h3>jQuery ajax() tutorial</h3>
        <p>
            We will learn to use this method by making GET and POST
            request to JSON Placeholder API. Which provides us
            with fake/dummy APIs and data to test our request handling
            code that works on data accessed through external URLs.
        </p>
    </header>
    <button id="get-request">Get a Post</button>
    <main id="posts-container">
    </main>
  
    <script src=
    </script>
    <script>
  
        // We will write our code here
        $("#get-request").click(() => {
            post_num = Math.floor(Math.random() * 100)
            if (post_num === 0) {
                post_num = Math.floor(Math.random() * 100)
            }
  
            const URL =
                `https://jsonplaceholder.typicode.com/posts/${post_num}`
            $.ajax({
                url: URL, method: "GET", success: function (result) {
                    user_id = result.userId;
                    post_title = result.title;
                    post_body = result.body;
  
                    post_html =
                        `<hr>
                            <h2>${post_title}</h2>
                            <h5>Contributed by: ${user_id}</h5>
                            <p>${post_body}</p>
                        <hr>
                        `
                    $("#posts-container").append(post_html)
                }
            })
        })
    </script>
</body>
  
</html>


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads