What is the use of jQuery.ajax() method?
Last Updated :
29 Jul, 2024
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=
"https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js">
</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:
Ajax in JQuery
Similar Reads
What is the use of delay() method in jQuery ?
In this article, we will see how to use the delay() method and why to use it in jQuery. The delay() method is used to set a timer to delay the execution of the next item in the queue. Syntax: $(selector).delay(para1, para2); In the below example, first, we create a div of size 250px X 200px and set
1 min read
What is the use of css() method in jQuery ?
In this article, we will see how to use css() method to set the styles on elements dynamically using jQuery. The css() method is used to change the style property of the selected element. basically, The CSS() method is used to get the value of a certain CSS property that has been applied to a specif
2 min read
What is the use of html() method in jQuery ?
The html() method in jQuery is used to get the contents of the first element in the set of matched elements or is used to set the HTML contents of every matched element. It returns the content of the first matched element. This function does not accept any arguments. Syntax: $(selector).html();Appro
4 min read
What is the use of append() method in JQuery ?
In this article, we are going to see how to use the append() method in jQuery. The append() method is used to insert new content inside an existing element. There are some other methods also that provide to insert new content inside an existing element and these are - prepend(), html(), text(), befo
2 min read
What is the use of param() method in jQuery ?
In this article, we will learn about the param() method which is an inbuilt method provided by jQuery. This method is used for creating a serialized representation of an object. The method will recursively serialize deep objects for trying to work with modern languages like Ruby on Rails or Python.
3 min read
What is the use of delegate() method in jQuery ?
jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax inte
2 min read
What is the purpose of fadeToggle() method in JQuery ?
In this article, we will see how to create a fadeToggle effect using jQuery. The fadeToggle effect can be created using fadeToggle() method.The fadeToggle() method is used to toggle between the fadeIn() and fadeOut() methods. If elements are faded in, fadeToggle() will fade out. If elements are fade
1 min read
What is the use of .each() function in jQuery ?
The each() function in jQuery iterate through both objects and arrays. Arrays that have length property are traversed from the index 0 to length-1 and whereas arrays like objects are traversed via their properties names. Syntax: $.each('array or object', function(index, value){ // Your code }) In th
2 min read
Which parameters are being used for the jQuery Ajax method ?
In this article, we will see the parameters that are used in the jQuery Ajax method along with understanding their implementations through the illustrations. The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request. Generally, the ajax() method is used in all the r
6 min read
What are various methods to make ajax request in jQuery ?
In this article, we will see the various methods to make Ajax requests in JQuery. An Ajax request is made to get a response from a server or external website. Ajax Request and Response is the communication between the client and server. jQuery's AJAX methods allow you to request text, HTML, XML, or
4 min read