Search code examples
javascriptjqueryhtmljquery-load

How to load dynamic content into a DIV using JQuery


I have a div:

<div id="content"></div>

And when the page is loaded i call a .load(). This load takes around 10 minutes to finish and during the execution its PHP file return some information telling about the execution status, something like Linux loading. I want do put this information inside the div #content dynamically, but .load() is putting only at the end of the execution. Someone can help me please to do this?

The .load() call:

$("#content").load("/admin/ajax/analyse.php");

Solution

  • jQuery's ajax interface does not provide a way to get progress updates for a response (even though it claims to be a superset of the browser's native XMLHttpRequest object). Apparantly, such a use case is inconceivable to the jQuery developers:

    No onreadystatechange mechanism is provided, however, since success, error, complete and statusCode cover all conceivable requirements.

    By using the an XMLHttpRequest directly, you can read the current progress of a response in an onreadystatechange event handler:

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/admin/ajax/analyse.php", true);
    xhr.onreadystatechange = function receiveUpdate(e) {
        $("#content").html(this.responseText);
    }
    xhr.send();
    

    This works in the latest versions of most browsers including IE 10, Chrome, and Firefox.

    Demos: