I am using Magento 2.2.1, I am trying to trigger ajax call after Full page load. I tried with below scripts but no luck. Did anyone faced this issue and found any solution for it.

<script type="text/x-magento-init">

2 Answers 2

var chkReadyState = setInterval(function() {
    if (document.readyState == "complete") {

        // finally your page is loaded.
        // Your ajax call here!! 
        // Clear interval to avoid multiple ajax calls
}, 100);
  • Have you tried this ?
    – mighty_hk
    Commented May 8, 2018 at 6:47

Let’s take a look at this basic example:

        <meta charset="UTF-8">
        <title>Ajax Call After Page Load</title>

        <!-- 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>
        //When the page has loaded.
        $( document ).ready(function(){
            //Perform Ajax request.
                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.
                error: function (xhr, ajaxOptions, thrownError) {
                    var errorMsg = 'Ajax request failed: ' + xhr.responseText;

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

Hopefully, you found this tutorial useful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.