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

open a new window with a reference based on the name

In order to obtain a reference to the currently open window, I utilize the following code: var refWindow = window.open("mypage1", "name_mypage"); If I wish to close the window, I simply use this command: refWindow.close(); When I refresh the screen (by ...

Automatically updating client-side values in AngularJS using setInterval()

Implementing a value calculator on the client side using AngularJS. I need to update the main value of the calculator every 5 minutes with setInterval(). This is my AngularJS code: $http({method: 'GET', url: '../assets/sources.json'} ...

How does the question mark symbol (?) behave when utilizing it in response? Specifically in relation to data, the API, and the fetch API

Have you encountered the curious sequence of symbols in this context? data?.name Could you explain the significance of the question mark (?) between 'data' and the period? ...

Tips for transferring data from a pop-up or modal window to the main window in ASP.NET MVC

Currently, I am in the process of developing a contact form within ASP.NET MVC. This contact form will allow users to easily attach regular files through traditional file and browse functions. Additionally, users will have the option to search for a specif ...

How can you simultaneously send FormData and String Data using JQuery AJAX?

Is there a way to upload both file and input string data using FormData()? For example, I have several hidden input values that also need to be included in the server request. html, <form action="image.php" method="post" enctype="multipart/form-data"& ...

Issue: $injector:unpr Unrecognized Provider: itemslistProvider <-

I've spent several days debugging the code, but I can't seem to find a solution. I've gone through the AngularJS documentation and numerous Stack Overflow questions related to the error, yet I'm still unable to identify what's caus ...

Change PHP code to a JSON file format

I am currently learning Laravel and my current focus is on how to send a JSON file from the back end to the front-end. I intend to utilize this JSON data to generate a graph. Within my model, I have created a function that retrieves values and timestamps ...

Utilize Jquery to easily interact with RadComboBoxes

Is there a way to capture all RadComboBoxes change events in JQUERY for ASP.NET? $("input[type='text']").Change(function() { alert('changed'); }); In this example, I am specifying the input type as "text" because RadComboBoxes hav ...

Unable to extract attributes from a different model within Sails.js

I'm working on populating a customer model with attributes from the address.js model. However, when trying to post JSON using Postman, I keep getting a 500 Validation Error and struggling to pinpoint the cause of the issue. Any assistance would be gre ...

Issue with triggering (keyup.enter) in Angular 8 for readonly HTML input elements

My goal is to execute a function when the user presses Enter. By setting this input as readonly, my intention is to prevent the user from changing the value once it has been entered. The value will be populated from a popup triggered by the click attribut ...

JavaScript stylesheet library

What is the top choice for an open-source JavaScript CSS framework to use? ...

Angular Bootstrap: How to Resolve the Error "Function $(...).collapse() is Undefined"

I'm a beginner with Bootstrap and I'm attempting to trigger the .collapse() function using JavaScript within an Angular controller when a user clicks on a link. The goal is to close the collapsible navbar when a link is clicked, as the routing in ...

Efficiently transferring a style property to a child component as a computed property in Vue.js

Currently, I am facing an issue that involves too much logic in my inline style, which I would like to move inside a computed property. While I understand that this is the correct approach, I am unsure of how to implement it. To provide a clearer understa ...

Is there a way to temporarily toggle classes with jQuery?

Incorporating ZeroClipboard, I have implemented the following code to alter the text and class of my 'copy to clipboard button' by modifying the innerHTML. Upon clicking, this triggers a smooth class transition animation. client.on( "complete", ...

What is the best way to interact with the member variables and methods within the VideoJs function in an Angular 2 project

Having an issue with accessing values and methods in the videojs plugin within my Angular project. When the component initializes, the values are showing as undefined. I've tried calling the videojs method in ngAfterViewInit as well, but still not get ...

Locally hosted website failing to transfer login details to external domain

Having trouble with an ajax call that is supposed to retrieve data from a web page, but instead returns a jQuery parse Error. Even though I can access the page directly, the ajax call doesn't seem to be working and storing the result properly. Below ...

How can I turn off credential suggestions in a React JS application?

Is there a way to disable managed credential suggestion on a React JS web page using a browser? I have tried using the autoComplete=off attribute and setting editable mode with an onFocus event, but the password suggestions are still appearing. Any help wo ...

issue encountered during resource provider setup

Below is my code snippet where I'm attempting to populate a table using ngResource in a RESTful manner. However, when I include configuration directives, I encounter an uncaught object MINERR ASST:22 error. var app = angular.module('infra&apo ...

What is the best way to reset the scroll position of a div when you stop hovering over a link?

Can anyone help me figure out how to reset the scroll wheel when hovering over dropdown menu items? I've tried multiple solutions found online, but none seem to be working for me. If you have any ideas on how to accomplish this, please let me know! f ...

Tips for toggling the visibility of a <div> element with a click event, even when there is already a click event assigned

No matter what I try, nothing seems to be working for me. I'm looking to hide the <div id="disqus_thread"> at first and then reveal it when I click on the link "commenting", after the comments have loaded. This particular link is located at the ...