The global variable remains unchanged after the Ajax request is made

I am attempting to utilize AJAX in JavaScript to retrieve two values, use them for calculations globally, and then display the final result. Below are my code snippets.

   // My calculation functions will be implemented here

   var value1 = 0;
   var value2 = 0;
   MakeRequest(); // Once MakeRequest() is executed, value1 and value2 should be 10 and 20 respectively.
   var total = value1 + value2;
   console.log(total); // The output remains zero because value1 and value2 are still at 0.


// Request AJAX
    function createXMLHTTPObject(){
        var ajaxRequest;  // The variable responsible for Ajax functionality!

        try{
            // IE 7+, Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
            return ajaxRequest;
        } catch (e){
            // Internet Explorer
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                return ajaxRequest;
            } catch (e) {
                try{
                    // Internet Explorer 5, 6
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                    return ajaxRequest;
                } catch (e){
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
                }
            }
        }
    }

    // Create a function to handle data received from the server
    function AjaxRequest(url,callback,method){
        var req = createXMLHTTPObject();
        req.onreadystatechange= function(){
                if(req.readyState != 4) return;
                if(req.status != 200) return;
                callback(req);
        }
        req.open(method,url,true);
        req.send(null);
    }

    function AjaxResponse(req){
        var respXML=req.responseXML;
        if(!respXML) return;
        value1=respXML.getElementsByTagName("value1")[0].childNodes[0].nodeValue;
        value2= respXML.getElementsByTagName("value2")[0].childNodes[0].nodeValue;
        console.log("the value1 is "+ value1);  // Successfully displaying the values
        console.log("the value2 is "+ value2);
    } 

    function MakeRequest(){
         AjaxRequest("values.xml",AjaxResponse,"get");
    }
  1. My primary question pertains to why total = value 1 + value2 remains at 0. I have declared them as global variables and updated within makeRequest(), however, the values do not seem to update. How can I successfully update value1 and value2 for external use?

  2. I basically copied the ajax request codes from an online tutorial. One part that baffles me is when I invoke the MakeRequest() function, it triggers AjaxRequest("values.xml",AjaxResponse,"get"); However, the AjaxResponse(req) requires a "req" parameter, which is missing in the actual call within AjaxRequest("values.xml",AjaxResponse,"get"). Despite this discrepancy, the code functions correctly. Can you clarify this aspect for me?

Answer №1

One of the main reasons why AJAX calls are so effective is because they operate asynchronously. This means that your code runs in real-time, following a specific timeline:

var value1 = 0;
var value2 = 0;
MakeRequest();           // An AJAX REQUEST is initiated, operating on its own timeline
var total = value1 + value2;
console.log(total);     // At this point, the total will still be 0 since the AJAX response has not yet returned


// MakeRequest initiates an AJAX request and once it is successful, it can update value1 and value2, then calculate the total  

The calculation total = value1 + value2 should occur only after the AJAX request successfully returns if you want value1 and value2 to rely on the result of the AJAX request.

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

Problem with locating elements using Selenium xpath

While using selenium and xpath, I encountered a peculiar issue. On a page, there are 25 <a> tags with nested <img/> tags. I am trying to retrieve all these elements using the findElements() method. Interestingly, upon inspecting the page source ...

Understanding the visibility scope in JavaScript's object-oriented programming

I have the following code snippet: function A() { this.AFunction = function() { var b = new B(); b.BFunction(); } } function B() { this.BFunction = function() { // some code $.ajax({ url: url suc ...

Transferring an IONIC project to a different computer

Let me outline the current situation I am facing - I primarily work as a firmware developer rather than a software developer. Recently, a team member who was responsible for developing the front end of an application in IONIC has left the company, leaving ...

Guide to assigning unique identifiers to all elements within an array using JavaScript

I have an array of objects with numeric keys that correspond to specific data values. I am attempting to restructure this object in a way that includes an 'id' field for each entry. Here is the original object: [ { "1": "data1", "5": "d ...

Adding ngChange programmatically in Angular without using attributes is a common challenge faced

I am attempting to replicate the functionality of the ng-change attribute within a directive without making changes to the HTML (thus excluding the use of the ng-change property). After examining the Angular source code for the ngChange directive, I have ...

Tips for applying Json in Asp.net Core

Looking for some guidance on displaying gallery images using JSON as a beginner. Can anyone provide some assistance and walk me through the coding process? Here is what I've done so far: This is how I displayed the images in my razor view:enter imag ...

Activate the click event repeatedly in a loop

I am currently working on a bookmarklet to extract information from my Indiegala bundles that I have purchased. Instead of gifting the entire bundle, I prefer sending individual games one or two at a time as it is more convenient with the individual gift U ...

Executing a Node.js script using an absolute path

In the process of developing a basic app using Node.js and Express, I've encountered an issue. The script is located at path/to/script/server.js. When I run this script with node server.js while in the correct directory, everything functions correctly ...

What is preventing ShowViaLink() from functioning properly in Firefox and Internet Explorer?

I am facing an issue with my webpage where the navigation does not work on Firefox or IE, but it works perfectly fine on Chrome. I suspect that the problem lies in this code, as when I made changes to it, the navigation stopped working on Firefox & IE: ...

Unusual behavior observed when altering properties of checkboxes

Here is the code snippet in question: <table border="1" style="margin:0 auto;"> <tr> <td class="pointer" style="padding: 2px;"><input style="margin-left: 2px;" type="checkbox" name="nuovoCheck" id="newCheckId" value="N" /& ...

Enabling HTTPS as the default for axios HTTP requests

My challenge lies in setting up an ajax request with axios that specifically needs to be made over https. axios.get('/relativeurl') .then((response) => { console.log(response); }) .catch((error) => { console.log ...

There seems to be an issue with the transaction payload in the Cardano wallet when submitting an

I am attempting to send a previously signed transaction from cardano-cli using the cardano-wallet endpoint: https://localhost:8090/v2/proxy/transactions Here is how the signed transaction appears: txBody = { "type": "Tx MaryEra&q ...

Troubleshooting: Issues with Jquery's replaceWith function

I'm facing an issue with a table I have that includes a button in one of its columns. The button is supposed to toggle the class of the current row in the table and then replace itself once clicked. $(document).ready(function() { $(".checkOut"). ...

In the strict mode tree, a reference named "grid" has been discovered

I encountered the following warning in the console: Warning: A string ref, "grid", has been found within a strict mode tree. String refs can potentially lead to bugs and should be avoided. It is recommended to use useRef() or createRef() instead. T ...

Database hosted on Heroku platform

Curious to know, if you utilize Heroku for hosting, what database do you prefer? Do you lean towards PostgreSql, MongoDB, or another option altogether? I initially developed a bot using sqlite3, but quickly discovered that Heroku does not support it and ...

Adding supplementary documents within the app.asar file via electron

This is a Vue application using electron-builder. { "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "electron:build": "vue-cli-service electron:build", "electron:serve": "vue-cli-service electron:serve", ...

Adjust the size of three panels (left, middle, right) using Javascript, ensuring that the middle panel remains unchanged in size

I am a newcomer to JavaScript and currently working with HTML, CSS, and JS files. I have three panels - left, center, and right - that I want to resize. The left panel resizes correctly when dragging the column border. https://i.stack.imgur.com/LxhUX.png ...

Where am I going wrong in my attempts to use a callback function?

I am currently attempting to implement a callback function for this particular JavaScript function. function Filtering_GetSite(siteElement) { $.ajax({ type: "POST", url: "samle.asmx/f1", data: "", contentType: "application/json; charset= ...

Can the hasClass() function be applied to querySelectorAll() in JavaScript?

As a beginner in javascript and jquery, I recently attempted to manipulate classes using the following code snippet: if ($(".head").hasClass("collapsed")) { $(".fas").addClass("fa-chevron-down"); $(".fas&qu ...

Steps for updating the nested array object using the unique identifier: "id"

Having trouble updating the nested state array in my module where users scan QR codes to update tracking numbers. Currently, I am using react js for frontend and Laravel for backend. Issue: When scanning the QR code, the tracking number is not being set t ...