Send Ajax request after page has loaded.

This is a tutorial on how to send Ajax requests after the web page has loaded. In this guide, I will be using the JQuery library to send a simple Ajax request after the document has finished loading.

Let’s take a look at this basic example:

An explanation of the code above:

  1. We create an empty DIV element. We give this element the ID “content” so that we can easily reference it and manipulate it with JavaScript.
  2. We included the JQuery library, simply because it eliminates a lot of the tedious work that a regular vanilla JavaScript Ajax request often requires.
  3. We use the JQuery ready function in order to make sure that our JavaScript does not execute until the page has loaded.
  4. Inside the ready function, we perform a simple GET Ajax request to a file called “test.html”. If you are testing the script above, simply create a file called “test.html” and add it to the same folder that this web page is situated in. Make sure that you add some text to the file. I added “Hello World!” to mine.
  5. If the Ajax request is carried out successfully (if a 200 OK HTTP response code is returned), then the success function is executed. Inside this success function, we simply add the data that is returned from our request to the “content” div by using the html function. The html function will replace whatever is inside the “content” div.
  6. We also setup an error function, which will display an error message in the “content” div if the request fails for whatever reason (404 not found or 500 internal server error, etc).

Hopefully, you found this tutorial useful!

Comments

comments