Is JavaScript code synchronized with DOM manipulations during an AJAX request?

Within the code below, I have attempted to demonstrate the execution flow of synchronous ajax requests. Two ajax requests are sent synchronously with a delay between them. The issue arises when only "Request 1" is displayed in the console, but the response text does not update in the DOM. It's only after the delay and completion of the second request that the first response text is finally shown, followed by the second response text.

The question arises as to why the first ajax response text takes longer to update in the DOM, even though the server-side response was received before the delay began?

index.html
-----------

<!DOCTYPE html>
<html>
<body>
    <!--Calls the function synchronously(async=0/false)  -->
    <button type="button" onclick="loadDoc('ajax_info.txt')">Synchronous Operations</button> 

    <p id="result1"></p>
    <p id="result2"></p>

</body>
<script type="text/javascript">
    function loadDoc(url) {

        console.log("Entered ");

        ajax(1,url,"result1");
        for(i=0;i<1000000000;i++){}
        ajax(2,url,"result2");

        console.log("Exit");
    }

    function ajax(requestNo, url, div) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById(div).innerHTML = this.responseText;
                console.log("Request " + requestNo);
            }
        };
        xhttp.open("get", url, 0);
        xhttp.send();
    }
</script>
</html>

ajax_info.txt

--------------
This is the content from a txt file.

Answer №1

Upon further inspection, it appears that there may be an issue with your response. To test this theory, I utilized a publicly accessible fake endpoint and was able to successfully reproduce the expected outcome: https://jsbin.com/kojowaneda/1/edit?html,js,console,output

One notable difference between the provided code snippet and yours is the argument passed in the function call:

<button type="button" onclick="loadDoc('https://jsonplaceholder.typicode.com/todos/1')">Synchronous Operations</button>

Additionally, it is recommended to utilize setTimeout for handling timeouts rather than relying on a for loop.

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

Strange alignment issues occurring solely on certain PCs

Currently, I am in the process of developing a website for a client who has requested that it be an exact replica of the mockup provided. However, I have encountered some issues with the headers and certain divs that contain background elements. Surprising ...

JavaScript Geocoding does not initiate the search process

Currently in the process of moving some Google Maps functions to a separate file. In my main file, I have a function search() that sets up a workflow with the other file included. The issue I'm facing is with the geocoder.geocode() function, which was ...

Determine image size (pre-upload)

One of the requirements for a project I am working on is to verify the dimensions (width and height) of images before uploading them. I have outlined 3 key checkpoints: 1. If the dimensions are less than 600 X 600 pixels, the upload should be rejected. ...

When using Angular 2, the array.splice() function is causing the elements to be removed from the

I am currently working with an HTML table that has default checked rows. <table> <tr> <th></th> <th>Id</th> <th>Name</th> <th>Initial</th> </tr> ...

Is there a way to verify if all the values in an array of objects are identical?

In this scenario, my array consists of entries with identical address IDs but different phone types and numbers. I am in need of assistance with iterating through the array to extract the phone type and number when the address ID matches. I seem to encount ...

display the text from the template after selecting it (including both the text-field and value-field)

I'm currently utilizing BootstrapVue. In my b-form-select component, I display the name (as the text field) in the selection within my child.vue and emit the age (as the value field) to my parent.vue. This functionality is functioning as intended. H ...

Angular Bootstrap multi-typeahead component glitches

Currently, I am utilizing the bootstrap angular typehead feature. When using it for a single input field, everything functions as expected. However, upon attempting to implement multiple instances, I encounter an issue where one dropdown interferes with th ...

What causes the console.log statement to return undefined in this code snippet?

var elements = $('.container'); var links = new Array('home', 'about', 'services', 'gallery', 'contact'); for (var j = 0; j < links.length; j++) { elements.on('click', 'a[hre ...

Passing key value pairs with jQuery's get method

For my project, I am developing a universal function that interacts with different types of data and executes ajax get requests based on the data. At times, I need to make a get request like this: {option1: 'delete', id: idToRemove}, and other ...

Assume we have two positive integers, N and X. In this scenario, N represents the total number of patients, while X denotes the time duration, measured in minutes, between the arrival

Suppose you are given two positive integers N and X. Here, N represents the total number of patients while X indicates the time duration (in minutes) after which a new patient will arrive. The doctor only provides 10 minutes to each patient for consultatio ...

What is the best method for extracting an element from a forEach loop?

Could you please help me figure out how to extract the value of AllMainSongsIndex from the loop and demonstrate its usage? songsItems.forEach((element, i) => { let Allcovers = element.querySelectorAll(".cover") Allcovers[0].src = s ...

Is it possible for me to utilize window.top within the .js file?

Within my GWT code, I am transferring a variable to a JSP file. The process looks like this: <html> <head> <script type="text/javascript"> alert("Inside the JSP file"); var criticalPath = window.top.criticalPath; ...

Using Handlebars to incorporate altered ajax information into a template

Currently, I am exploring ways to utilize manipulated data from an ajax request in conjunction with Handlebars. Within my database, the data is stored as an object like so: {"1 year":"$4.95", "2 years":"$3.95"} My objective now is to make use of this d ...

JavaScript Inferno" - Similar to the concept of "DLL Hell

I'm working on an ASP.NET webpage that has the following structure: <%@ Page Language="VB" MasterPageFile="~/LGMaster.master" AutoEventWireup="false" Inherits="com.Genie.PresentationLayer.Web.frmPNList" title="Primary Nominals results list - RESTR ...

The Push Over Menu is malfunctioning and not functioning properly

I am facing an issue with pushing my menu along with the content to the right. The JS code I have is not working as expected. When I click on <div class="menu-btn toggle"></div>, the menu does not trigger. Can someone help me understand why thi ...

Utilize a ModalPopupExtender to showcase a table, allowing users to select a record and seamlessly pass it to the form for

On my website, I have a search screen with multiple parameters that may return numerous records. However, the user usually only needs to see details for one record. If multiple records are returned, I want to show a modal popwindow containing a data grid w ...

Display the country code according to the option chosen by the user in the dropdown menu

To enhance user experience, I am implementing a feature where the user can select their country from a drop-down list and then have the corresponding country code displayed in a text field for easy entry of their phone number. Below is the list of countri ...

Is there a way to dynamically apply CSS to a modal?

I have been busy creating a modal, and I wanted to share the HTML code with you. Take a look at the style tag, where I am customizing the .modal-content CSS class and .modal-dialog CSS class. <script type="text/ng-template" id="Data.html"> <styl ...

Persistent vertical menu dropdown that remains expanded on sub menu pages

I am struggling to understand how to keep my menu sub items open when on the active page. Although I have tried similar solutions, I have not been successful in implementing them. I apologize if this question has been asked before. My approach involves usi ...

Error triggered by .click() leading to confirmation() being repeated and resulting in duplicated data

Creating a Functional CRUD Application After successfully implementing a CRUD CMS using AJAX, everything was running smoothly until I introduced pagination with click ajax events. This script, which I will share below, seems to be causing some issues. +- ...