1

I have a function which does validation using ajax. It populates the array by reading the xml file. Right after reading the file, it checks whether the email supplied by the user is contained in the xml file. My code works fine and it solves the problem. However it is using synchronous open method (which as far as I know is a bad practice). How do I make it asynchronous and be able to populate the array?

    function validateBlackListedEmail(emailAddress){
    var http = new XMLHttpRequest();
    var emails = [];

    http.onreadystatechange = function(){ 
        if(http.readyState == 4 && http.status == 200){
            var xmlDoc = http.responseXML
            var x = xmlDoc.getElementsByTagName("email");

            console.log(x.length);
            var xlength = x.length;

            for (var i = 0; i < xlength; i++){
                var y = x[i].childNodes[0].nodeValue;
                emails.push(y);
            }
                console.log(emails);

        }
    }
    http.open("GET","emails.xml",false);
    http.send();

    if (emails.includes(emailAddress))
        return true;
    else
        return false;

}
Haris Ghauri
  • 547
  • 2
  • 7
  • 27
  • If you make the ajax call asynchronous (which you should), `validateBlackListedEmail` **cannot** return the result of the check. See the linked dupetarget for why and what to do instead. – T.J. Crowder Nov 07 '16 at 18:11

0 Answers0