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");
}
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?
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?