In this tutorial, we will show you how to send an Ajax request after the web page has loaded.
In this guide, we will be using the jQuery library to send a simple Ajax request after the document has finished loading.
Let’s take a look at a basic example.
<html> <head> <meta charset="UTF-8"> <title>Ajax Call After Page Load</title> </head> <body> <!-- Content is blank by default --> <div id="content"></div> <!-- Include the JQuery library --> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script> //When the page has loaded. $( document ).ready(function(){ //Perform Ajax request. $.ajax({ url: 'test.html', type: 'get', success: function(data){ //If the success function is executed, //then the Ajax request was successful. //Add the data we received in our Ajax //request to the "content" div. $('#content').html(data); }, error: function (xhr, ajaxOptions, thrownError) { var errorMsg = 'Ajax request failed: ' + xhr.responseText; $('#content').html(errorMsg); } }); }); </script> </body> </html>
An explanation of the code above.
- 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.
- After that, we include the jQuery library. jQuery is useful as it eliminates a lot of the tedious work that regular vanilla JavaScript Ajax request often require.
- We use the JQuery ready function. This function is important as it prevents our JavaScript code from executing until the page has loaded.
- 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 “test.html” file and then add it to the same folder that your web page is currently situated in. Make sure that you add some text to the file. For example, I added “Hello World!” to mine.
- If the Ajax request is successful (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.
- We also setup an error function. This error function will display an error message in the “content” div if the request fails. For example, if the Ajax request encounters a 404 Not Found or 500 internal Error.
Hopefully, you found this tutorial useful!