Pretty cool stuff for pretty cool people.

Menu

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:

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<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 execute,

//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){

varerrorMsg='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.

We included the JQuery library, simply because it eliminates a lot of the tedious work that a regular vanilla JavaScript Ajax request often requires.

We use the JQuery ready function in order to make sure that our JavaScript does not execute 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 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.

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.

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).