Using AJAX asynchronously in JavaScript commands synchronization

After researching similar questions on SO without finding a satisfactory answer, I encountered an issue with synchronous AJAX calls in my HTML/JavaScript page. Mozilla has deprecated some functionality related to synchronous requests, making it necessary for me to adapt my code to handle asynchronous requests better.

In response to this challenge, I have attempted to modify a generic "make web request" function that my application utilizes. However, my current approach is not yielding the desired results.

var webResponse = null;

function webCall(action, type, xmlBodyString) {
console.log("In webCall with " + type + ": " + action);
webResponse = null;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
    if (xmlhttp.readyState == 4)
    {
        if (xmlhttp.status == 200) {
            webResponse = xmlhttp.responseXML;
        } else {
            var statusTxt = xmlhttp.statusText;
            if (statusTxt == null || statusTxt.length == 0) {
                statusTxt = "An Unknown Error Occurred";
            }
            throw "ERROR " + xmlhttp.status + ":" + statusTxt;
        }
    }
}
xmlhttp.open(type, action, true);
if (xmlBodyString == null) {
    xmlhttp.send();
} else {
    xmlhttp.setRequestHeader("Content-Type", "text/xml");
    xmlhttp.send(xmlBodyString);
}

for (var i = 0; i < 20; i++) {
    if (webResponse != null) {
        break;
    }
    window.setTimeout(nop, 250);
}
if (webResponse == null) {
    throw "Waited 5 seconds for a response, and didn't get one.";
}
console.log("Responding with " + webResponse);
return webResponse;
}

function nop() {
}

Despite setting up a mechanism to wait a maximum of 5 seconds for a response, the code exits prematurely instead of actually waiting. Even when tested in a fiddle, the issue persists. http://jsfiddle.net/Z29M5/

I am seeking assistance in resolving this discrepancy. Any help would be greatly appreciated.

Answer №1

It's not possible to achieve synchronous behavior in plain JavaScript on browsers right now. Stick to using asynchronous requests to avoid getting stuck in callback hell, which is a common issue in event-driven systems lacking language support.

Unless you're willing to limit your browser compatibility (mainly to just Firefox currently), generators can give you code that appears synchronous. However, for a more seamless experience, consider using languages that compile into JS and offer support for synchronous-like code. One such example from a few years ago is https://github.com/maxtaco/tamejs.

Answer №2

Initially, to alleviate the struggle, utilizing asynchronous code in an asynchronous manner is the optimal approach. It requires a distinct methodology, that's all.

Moreover, concerning your specific inquiry, this is the functionality of your 'delay' loop:

For twenty iterations
  if a response is received, stop
  set a timeout for 250ms
repeat process

(The entire loop completes all 20 cycles instantly. Response will not be obtained)

. . . after 250ms

execute the initial setTimeout callback, namely nop

carry out the subsequent...

A viable solution eludes me at the moment, except by relocating your processing code within the AJAX call back, the ideal location for async code regardless.

Answer №3

Consider the benefits of managing a queue of requests and handling them sequentially as each ajax call returns.

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

Convert data in JavaScript and send it as a string in PHP

I'm currently facing a small issue with my JavaScript code. Specifically, I am using AJAX and attempting to retrieve a variable in PHP. Everything seems to be working fine except for the "param" data. Below is the snippet of my code: $('#sign ...

Error: Unable to execute setState in React Native

Why am I receiving an error stating that this.setState is not a function? I'm having trouble understanding why my code isn't working as expected. import React from 'react'; import axios from 'axios' import { StyleSheet, Text ...

Nodemon failing to trigger auto-refresh

My journey with learning node.js using nodemon has hit a roadblock. Despite following tutorials and installing everything exactly as shown, I'm facing an issue. Whenever I enter 'nodemon index.js' in the terminal, it hosts properly but any c ...

Instead of relying on traditional AJAX for receiving remote commands, consider using a new Image object in your code like this: `var

How efficient is the following method: var i = new Image(); i.src = 'http://secondary.domain.com/command.gif?command=somecmd&rand=' + ...epoch time....; ... utilizing mod_rewrite to redirect the above URL to a PHP script ... Is this an effe ...

Incorporate AJAX to update text values in the database using CodeIgniter

My code isn't working properly and I can't figure out what's missing. Here is the code snippet: View admin_page.php <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script type="te ...

Necessary workaround needed for HTML time limit

Our HTML page has been designed to automatically timeout after 10 minutes of inactivity. This functionality is achieved through the following code: function CheckExpire() { $.ajax({ type:'GET', url:self.location.pathname+"?ch ...

What causes the order of `on` handler calls to be unpredictable in Angular?

Below is the code snippet I have been working on function linkFunc(scope, element, attr){ var clickedElsewhere = false; $document.on('click', function(){ clickedElsewhere = false; console.log('i ...

Safeguarding form submissions using ajax: implementing csrf token or going without

My form is secured with a CSRF token, which I've heard is essential for maintaining form security. Whenever the form is submitted late, an error occurs, indicating that the CSRF token is working as expected. However, when submitting the form using aj ...

Tips for inserting a personalized image or icon into the ANTD Design menu

Can anyone help me figure out how to replace the default icons with a custom image or icon in this example: https://ant.design/components/layout/#components-layout-demo-side I attempted to do it by including the following code: <Menu.Item to="/" key=" ...

Establish boundaries for D3.js circle reports

I am currently working on a visualization project where I want to arrange cells with higher values to appear towards the top and left, similar to a gravity force. However, I am facing difficulties in keeping multiple circles within the boundaries of the re ...

A ReferenceError was thrown because angular is not defined within the angular-moment.js script

After spending an hour trying to figure out what went wrong, I still can't solve this problem. I've searched on stackoverflow for answers, but nothing seems to be helpful. The issue arises when trying to integrate Moment js into my project. Che ...

What could be the reason for the malfunctioning of the header() function in PHP

Currently, I'm utilizing AJAX to facilitate user registration for a service. Here's the code snippet for the submit button: <input type="button" id="register" name="register" class="btn btn-success" onclick="registration();" value="Register"/ ...

Save property using the useState hook

I am working on implementing a sorting function in the child component, where the props are passed in from the parent through an axios call. Should I: Store the prop in the child component's useState? Pass the parent's setState function as a pro ...

Unable to retrieve value 'includes' from null object

Currently, I am utilizing Vue.js along with JavaScript. In my code, there is an array of objects named products, each containing a special property called smallest_unit_barcode. My goal is to filter out only those products that have a barcode similar to a ...

What could be the reason why the toggleClass function is not being run

I've been running into a little issue with using the .toggleClass function in my code. It seems to work inconsistently, and despite reading various posts on the topic, I haven't found a solution that works for me. Could you provide some assistan ...

How can you ensure that the right data types are sent through ajax requests?

My goal is to ensure the server receives data in the correct data type when using ajax. For example, I want boolean values to be received as actual booleans, integers as integers (not strings), and so on. I attempted a solution where I sent the data as JS ...

One controller displays ng-repeats while the other does not

I have 2 controllers loading in different locations within my view. One controller works perfectly, but the other one does not show ng-repeats or appear in ng-inspector. I have confirmed that the http data is visible in the inspector. Both controllers are ...

Is there a way to incorporate text at the end of a row in HTML?

I have a photo and some text on my website. The photo is displayed on the left side, while the text appears nicely on the right side. Now, I am looking to include an additional block of text below the existing text. How can I accomplish this? What steps ...

identifies a data point from a combined dropdown menu

Is there a way to detect a specific value from a multiplied combo box? For example, when the value in one of the combo boxes changes to "2", a component is displayed. However, if the value in another combo box changes to anything other than "2", the compon ...

Retrieve the values and IDs for every span element within the form

I have been attempting to retrieve all span elements within a form and make them editable input text fields. Once you click away, they should revert back to span elements. I will provide a live example in the attached fiddle. I tried my hand at it, but the ...