XMLHttpRequest returns response before page is fully loaded

I’m trying to automate the search function at https://developers.arcgis.com/javascript/jssamples/#search/ using XMLHttpRequest, but the response is coming back before the results have loaded.

If you put a search term like Layer, Geoprocessor, Legend, etc. on the end of the url above and load the page, the #sample-thumbs div will contain links to samples that contain the search term. It takes about 10 seconds to load though, and the request returns before that, so the #sample-thumbs div is not yet present and the #samplesLoading div is still visible.

Here is my request function; I am checking that readyState is 4 and status is 200 before returning the response, so XMLHttpRequest thinks the page is fully loaded. The page is mostly complete, apart from the results div, which takes a further few seconds to load.

function doAjaxRequest (requestUrl, callback) {
    var ajaxRequest;

    // Create a request Object
    ajaxRequest = new XMLHttpRequest();
    ajaxRequest.onreadystatechange = function () {
        if (ajaxRequest.readyState == 4) {
            if (ajaxRequest.status == 200) {
    // Set response type
    ajaxRequest.responseType = "document";
    // Open url
    ajaxRequest.open("GET", requestUrl, true);
    // Send request

So, the question is, can I make XMLHttpRequest wait until #sample-thumbs has appeared? Or can I make a second request (or multiple requests) to the same page to check if this div has appeared yet? It seems like the XMLHttpResponse is just returning a snapshot, so should I be using another method to get a dynamic response, which will continue to update as the page loads?

Sorry, that’s actually three questions. Basically I’m asking if what I’m trying to do is possible with XMLHttpRequest, and if not, what else could I use?

Source: ajax

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.