0

Here is my code:

        function checkUsername(){
            var checkForm;

            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else {
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }

            xmlhttp.onreadystatechange=function() {
                if (this.readyState == 4 && this.status == 200) {
                    if(this.responseText == 'Username Available'){
                        checkForm = true;   
                        alert(checkForm);
                    }
                    else{
                        checkForm = false;
                    }
                    errorElement.innerHTML = this.responseText;
                }
            }
            xmlhttp.open("GET","unamechecker.php?str=" + str);
            xmlhttp.send();
            alert(checkForm);
            return checkForm;
        }

First alert() will output true no doubt. But second alert() will output undefined as the value of checkForm assigned true is in another function (defined inside the parent function) and do not have any value in it's function. I want to use the checkForm variable value in parent function as changed by sub-function. How can I acheive this?

Don't suggest to make checkForm global variable, as I have many methods on the same page have variable name checkForm.

Siraj Alam
  • 9,217
  • 9
  • 53
  • 65
  • you have a sync/async issue, not a scope issue. checkUsername() will return before the HTTP request returns and sets your flag. consider using a promise to solve your sync issue. – zim May 07 '17 at 19:26
  • SO the variable changed in the inner function will maintain its value outside the inner function? – Siraj Alam May 08 '17 at 03:52
  • yes, through the closure. but you have a timing issue. check the link provided at the top of your question, there is a ton of great info in there. – zim May 08 '17 at 17:30

0 Answers0