Menu Close

How to send an Ajax request after the page has loaded

Codeamend

Let’s see how to send an Ajax request after the web page has loaded.

Here, the ajax request performs to get the data from the url. Then it manipulates the data to the given id and loads the page successfully. If anything is wrong in the given url it will display the error message.

Example:

<html>
    <head>
        <meta charset="UTF-8">
        <title>Ajax Call After Page Load</title>
    </head>
    <body>       
        <!-- Content is blank by default -->
        <div id="content_blank"></div>
 
        <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){
                    $('#content_blank').html(data);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    var errorMsg = 'Ajax request failed: ' + xhr.responseText;
                    $('#content_blank').html(errorMsg);
                  }
            });
        });
        </script>
    </body>
</html> 
Posted in Ajax, HTML

You can also read...