The XMLHttpRequest fetches data before the page is completely loaded

I'm currently working on automating the search functionality of using XMLHttpRequest. However, I am facing an issue where the response is being received before the results finish loading.

If you append a search term like "Layer", "Geoprocessor", "Legend," etc. to the end of the URL provided above and load the page, the #sample-thumbs div will display links to samples containing the specified search term. The loading process takes approximately 10 seconds, causing the request to return prior to the completion of this process. As a result, the #samplesLoading div remains visible while the #sample-thumbs div is yet to appear.

I have included my request function below; I have added checks for readyState being 4 and status being 200 before returning the response. Despite this, due to the delayed loading of the results div, XMLHttpRequest believes the page is fully loaded even though the results div requires additional time 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) {
                callback(ajaxRequest.response);
            }
        }
    };
    // Set response type
    ajaxRequest.responseType = "document";
    // Open url
    ajaxRequest.open("GET", requestUrl, true);
    // Send request
    ajaxRequest.send(null);
}

Hence, my question is – Is it possible to make XMLHttpRequest wait until #sample-thumbs appears? Alternatively, can I make subsequent requests to the same page in order to check for the presence of this div? It seems that XMLHttpResponse is simply providing a static snapshot, prompting me to explore other methods for obtaining dynamic responses that continuously update as the page loads.

Apologies for the lengthy query, that actually equates to three questions. Essentially, I am inquiring whether my current approach with XMLHttpRequest is viable and if not, what alternative methods could be employed?

UPDATE: Here's a comprehensive code snippet. By setting a breakpoint at line 25 (.innerHTML += ...) and monitoring ajaxRequest.responseXML.querySelectorAll("#samplesLoading"), it is apparent that the loading div exists but the #sample-thumbs div does not.

function doAjaxRequest(requestUrl) {
  var ajaxRequest, loadingDiv;

  // Create a request Object
  ajaxRequest = new XMLHttpRequest();
  ajaxRequest.onreadystatechange = function() {
    if (ajaxRequest.readyState == 4) {
      if (ajaxRequest.status == 200) {
        document.getElementById("output").innerHTML += ajaxRequest.response.querySelectorAll("#sample-thumbs ul");
      }
    }
  };
  // Set response type
  ajaxRequest.responseType = "document";
  // Open url
  ajaxRequest.open("GET", requestUrl, true);
  // Send request
  ajaxRequest.send(null);
};

function doSearch() {
  var requestUrl;

  // build query url
  requestUrl = "https://developers.arcgis.com/javascript/jssamples/#search/";
  doAjaxRequest(requestUrl + document.getElementById("searchTerm1").value);
};
<div id="bcMain">
  <div id="cpRequest">
    <h2>Request test</h2>
    <label for="searchTerm1">Search Term 1</label>
    <input id="searchTerm1" type="text"/>
    <br><br>
    <button id="btnHttpRequest" type="button" onclick="doSearch()">Search</button>
  </div>
  <div id="cpResults">
    <h2>Results</h2>
    <div id="output"></div>
  </div>
</div>

Answer №1

When you send an XMLHttpRequest before the webpage finishes loading, there is a possibility that it will complete its request before the page fully loads.

A straightforward solution is to wait for the DOM to be ready before sending your request. Checking if ajaxRequest.readyState == 4 only confirms that the AJAX request is ready, not necessarily that the page has finished loading.

If your web application requires real-time data updates, simply relying on AJAX may not suffice. In the past, Comet and long polling were common solutions for this issue. However, now WebSockets offer bidirectional communication capabilities in web applications.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instructions for rotating a sphere simultaneously along the x, y, and z axes

Seeking assistance on how to properly rotate an image along all three axes using the Three Js library. Currently, rotation along one axis works fine, but when attempting rotation along all three axes, the results are abnormal. I have read about using quate ...

Find similarities between 2 observable arrays and store them in a new array using knockout data binding

There are three observable arrays set up as follows: a [1,3] b [ {"ID": 1, "Val": "Value1"}, {"ID":2, "Val":"Value2"}, {"ID":3, "Val":"Value3"}] c [] The goal is to compare array a with the IDs of elements in array b and then push the entire value of arr ...

Why isn't preventDefault() effective in this particular situation?

When attempting to obtain an OTP, the event.preventDefault() function is functioning properly. However, after updating the register-form for OTP verification, the event.preventDefault() function ceases to work. How could this happen? Your assistance is gr ...

The router.push function does not properly redirect to the specified path; instead, it just reloads the current page

I am a newcomer to NextJS and facing a challenge where I need to transfer data from the current page to another page. However, instead of loading the defined path in router.push as pathname: "/booking/checkout/", it loads the current page. I wan ...

Unable to show information within input field

I am attempting to present the value of my variable in a textBox using Jade, but I am encountering issues. I have tried the following options: value="#{startDate}" value="#{{startDate}}" value="{startDate}" value={{startDate}} I am aware that it is func ...

Set Expiration Dates

Just started coding for the first time and encountered an issue with Add Expires Header while testing my website on Gtmetrix. YSlow reported that I have 60 Add Expires Headers. http://www.whirloo.com/wp-content/plugins/contact-form-7/includes/css/styles.c ...

AngularJS Chart.js Element Instances

Feeling a bit stuck here, I'm importing JSON data into a smart table and creating charts based on that table. I want to implement cross-filtering so that when a filter is applied, the chart updates based on the filtered data in the table. The chart s ...

A guide to incorporating external CSS files in Angular 5 components using styleUrls

I have a unique setup where my Angular 5 application resides in a subdirectory within another parent application. The parent application consists of JSP and other AngularJS applications among other things. My goal is to include a CSS file from the parent ...

Achieving the Date format in electron with JavaScript

Is there a way to determine the date format currently being used on the device? For example, if I call a specific function, could it provide me with the current format? var dateFormat = getDateFormat(); console.log(dateFormat); MM/dd/YYYY Does anyone hav ...

Using the onclick event with an image created through PHP code

I am currently in the process of developing a dynamic image represented as a graph displaying the number of documents generated each day. This interactive image is being created using PHP, and I aim to improve user engagement by enabling them to click on t ...

Is there an issue with MVC5 in passing JSON data to Controller using Ajax?

I am working on implementing duplication checking in my MVC5/EF Code-First application. In the Asset View's Create() method, I use JavaScript to show/hide textboxes for adding a new location_dept/location_room: <div class="form-group"> ...

npm encountered an issue: EPERM error - the operation is not permitted and cannot unlink the file

Operating System: Windows 10. NPM Version: 6.9.0 Node Version: 12.4.0 I am currently developing an Expo application. I am attempting to install all the necessary packages for my Expo application using 'npm install'. However, I encountered an err ...

Having difficulty retrieving model values from the angular ui modal dialog

Being only on my second day in the world of Angular, I am trying to navigate around Angular UI and build my first modal dialog. The modal dialog displays properly, but I'm encountering an issue with using models within it. You can view my demo on Plun ...

What is preventing me from specifying a specific position in my multi-dimensional array?

My goal is to create a 3D version of an L-System, but I'm having trouble declaring elements in my multidimensional array. Even when I try to assign values to specific positions, the elements don't seem to update properly. For instance, if I write ...

Angular 2 can efficiently generate multiple HTTP requests simultaneously from a single HTTP request

Backend API's: url: [ { "name": "ABC", "occupation": "Student", "address_url": "http://www.sample.com/address/person=hgjgjgyyfhg" }, { "name": "ABC1", "occupation": "Carpenter", "address ...

Combining functions in React is a powerful way to create

Is there a way to create a single function that combines handleSelectAll and handleSelectNone for toggling options in a list of categories? Instead of using a toggle (on/off) approach, I believe having separate buttons for Select All and Select None is mor ...

"Effortless Email Alerts crafted with the power of jQuery and

My goal is to have email notifications sent out for every new upload, comment, or post. Currently, I am using a function call like this: notify($user_id, $submitter_id, $post_id); The notify() function processes these IDs and triggers the mail() functi ...

Dealing with a unique key error in a loop while using React and Google

I've implemented a react-google-maps component that successfully retrieves data from various locations. However, I'm encountering an error message in the console: Warning: Each child in a list should have a unique "key" prop. I made s ...

The UseEffect hook continues to run even if the dependency (router.query) remains the same

useEffect(() => { console.log('applying filter'); const updatedFilters = { status: { values: { label: router.query.status, value: router.query.status }, }, // Add additional filter properties here... }; ...

What is the best way to manage a vuex dispatch response?

Despite feeling like the answer is right in front of me, I'm waving the white flag and seeking suggestions. The challenge lies in my login form that submits to an AWS API and reacts to the result. The trouble starts when the handleSubmit method is tr ...