JQuery / javascript variable scope

var field1; var field2; function setUserFields() { $.ajax({ type: "POST", url: "url", dataType: "xml", complete: parseXml }); } function parseXml { $(xml.responseXML).find("myValue").each(function() { field1 = $(this).attr('attr1'); field2 = $(this).attr('attr2'); alert(field1 + ' ' field2); //shows correct values }); } setUserFields(); $(function() { alert(field1); //undefined in IE and Chrome | Gives correct value in FireFox alert(field2); //undefined in IE and Chrome | Gives correct value in FireFox }) 

I am not sending the exact code that I am running, as the code is rather complicated. If there are syntax errors in the submitted code, do not pay attention, as this is not the cause of my problem. The code works as expected in Firefox, but not in IE or Chrome. In addition, I can verify in Firebug lite that the order in which the code is run should not cause a problem. What I'm trying to do is call the web service, analyze the results and save the necessary information in a global variable for use in later functions, which I can only call after the DOM has finished loading. I run the setUserFields function before loading the document. The function is called and sets the variables, but the variables are only available in the parseXML () scope. Since I declared variables outside of all functions and set the variables inside the parseXML function, I would expect the variables to be set globally. However, only in firefox can I access variables without them undefined. I'm new to the javascript arena, so I may miss the obvious trap. I tried to walk for hours without any luck. Any help would be greatly appreciated.

+4
source share
2 answers

It's not a problem. This may be due to asynchronous AJAX calls.

The first letter in Ajax means “asynchronous”, which means the operation is executed in parallel and the completion order is not guaranteed. The async parameter for $ .ajax () defaults to true, indicating that code execution may continue after the request is made. Setting this option to false (and thus the call is no longer asynchronous) is very discouraged, as this may cause the browser to not respond.

jQuery.ajax()

+7
source

This is mainly a time issue.

your ajax code will not be executed when these variables are called

  alert(field1); //undefined in IE and Chrome | Gives correct value in FireFox alert(field2); / 

to fix the problem, make ajax call in the document. Even after that you can warn filed1 and field2,

I am very sure this is a matter of time due to the asynchronous nature of ajax

0
source

Source: https://habr.com/ru/post/1332297/


All Articles