7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
Advertisement
  1. Code
  2. JavaScript

Create a JavaScript AJAX Post Request: With and Without jQuery

In this article, we'll take a look at what AJAX is, why it is important, and how we can make an AJAX POST request with XHR, fetch(), and jQuery.

What Is AJAX?

AJAX stands for Asynchronous JavaScript and XML. AJAX is a technique in web development used to update content on a website without having to reload the entire page.

In an AJAX application, JavaScript is used to make real-time updates on parts of a page as the user interacts with it, thereby turning an otherwise static HTML page into a dynamic one.

Social networking web applications such as Facebook and Twitter use AJAX to update user feeds and notifications.

Let's take the Twitter web app as an example. After a specified time interval, the Twitter app makes an AJAX request to the server requesting new information. That is how the user receives the latest tweets on their feeds without having to reload the page.

All of this happens asynchronously; the user can continue to use the application while it requests information from the web server in the background. That's precisely why a user can scroll through their feed and react to tweets while the feed gets updated with new tweets.

In a traditional client-server request, the user will have to reload the page to get any new information from the server.

Benefits of AJAX

AJAX uses client-side JavaScript to fetch and display content in the background. This technique greatly improves the user experience, since the page doesn't have to be reloaded every time fresh content is needed.

Using AJAX leads to faster page renders because it can be used to update only the parts of the page that need to change, as opposed to reloading the entire page.

That also reduces the frequency of requests to the web server, which in turn leads to faster response times.

What Is a POST Request?

When performing API requests from the browser, the two HTTP methods you'll use for data transport are GET and POST. The main difference between these two methods lies in the way data gets sent to the web server application.

HTTP GET passes data to the server application in name and value pairs. These request parameters are appended to the URL. For example, the following is a URL for a GET request containing two request parameters that will be sent to the server:

www.mysite.com/id=12&name="chris"

Since data is visible in the URL, the GET method should never be used to transport sensitive information such as passwords and bank details.

Instead, the POST method should always be used to transport sensitive data. The POST method transports data in the request body. Data can be transported in JSON and XML formats.

How to Make an AJAX POST Request With XHR

You can use the XMLHttpRequest object (XHR) to communicate with a web server using the AJAX technique. This is the classic way to do AJAX, but it's not the best way now that the Fetch API is supported in modern browsers. In the next section, I'll show you a better way to make a POST request using fetch().

Now suppose we want to post the following data (a blog post) to a web server:

We can use XHR to post the data to a web server like so:

We began by converting the object to a JSON string to be transported via HTTP. Then we created an xhr object from the XMLHttpRequest class.

After that, we opened the request by calling the open() method, passing in the following options:

  • 'POST': the request method; we are posting data to the server
  • url: this is URL of the server to where we are posting the resource to
  • true: tells the browser to run the code asynchronously

We proceeded to set the request header, telling the server how to process the data we send over. Then we sent the body of our request.

When the request is successfully completed, the onload function will be invoked. Inside this function, we made an if check to ensure that the resource was successfully created on the server (as indicated by 201 status) before logging a message to the console.

You can also directly access values from a form in the page, like so:

Here we grab the values directly from the UI and display a response message to the user if the resource is created successfully.

How to Make an AJAX POST Request With fetch()

Another way to make AJAX calls in JavaScript is with the fetch() method. fetch() is an API utility method built into the web browser environment. It's a newer API than XMLHttpRequest, with modern features making it easier to use. I recommend you use fetch() for AJAX.

The following code makes a POST request to the server using fetch():

fetch() takes in the server URL and an object containing options like the HTTP method, request body, and request headers. Accept indicates what kind of response from the server the client can accept. Content-Type indicates the data format of the current request or response. Since our request has a payload, we have to use a content-type request header.

When the request is successfully executed on the server, we chain along the then() and catch() methods to handle the server response and errors respectively.

The first then() method simply converts the response data into a JavaScript object and returns the object. In the following then() method, we check for the status and log a success message to the console.

If any error is encountered along the chain, it will be handled by catch().

How to Make an AJAX POST Request With jQuery

So far, we have only used browser Web APIs to perform AJAX requests.

We can also execute an AJAX request using a library like jQuery. POST requests in jQuery are executed using the post() function.

I'll show you how to use jQuery to execute an AJAX request, but honestly with the new JavaScript Fetch API, there's really no need to import a whole library like jQuery just for AJAX.

Now let's make a POST request using jQuery instead:

post() takes in four arguments: the URL, request body, callback function, and data format.

When the request is successfully completed, the callback function passed to post() will be invoked. This function takes in the response and status from the post request, both as arguments.

In the callback function, we check for the request status and log a message to the console.

Conclusion

AJAX is a modern web technology used for updating page contents asynchronously. This means that a user can still interact with a page while the app uses JavaScript to fetch information from the server and update the page.

In this article, we looked at three ways to make AJAX post requests in a web application. We used the XMLHttpRequest object, the fetch method, and jQuery.

Because fetch() uses modern JavaScript features like promises, I strongly recommended using it over the other options. This is because you get to learn and use promise constructs like then(), catch(), and async/await.

With the availability of native APIs such as fetch() and XMLHttpRequest, there is no need to import a whole library like jQuery just to make AJAX requests in your application.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Scroll to top
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.