0

How can I get the variable to be equal to what is defined in the if statement? My first alert evaluates correctly but then loses scope. I need to take action outside of the $.get function.

function emailCheck() {

var emailExists;
var emailEntry = $("#email").val();

 $.getJSON('http://localhost:8080/ShoppingCart/ajax.do', function(responseJson) { 

     $.each(responseJson, function(index, item) { 

        if(emailEntry == item.email) {

            //Set to true when a match is found
            emailExists = true;
            return false;
        }
     });

    //alerts to true 
    alert(emailExists + " in get");


 });
//Need emailExists to be true here when match is found but it's undefined??
alert(emailExists + "end email check");

}

Mr Grimes
  • 17
  • 2
  • 1
    This has nothing to do with scope, and everything to do with asynchronicity. – adeneo Mar 07 '15 at 20:46
  • Sounds good, I will research that, thanks for pointing me in the right direction! – Mr Grimes Mar 07 '15 at 20:53
  • You're welcome, that answer should explain how it works pretty well, when it's async the javascript execution continues, while the ajax request is done in the background, as such the data simply isn't there when you're trying to use it. – adeneo Mar 07 '15 at 20:59
  • I get it now, I researched a lot but I was looking at the wrong topics. The answer you directed me to is awesome! Oh well, I learned a lot today so the lack of progress is well worth the new knowledge. Thanks again, made my weekend! – Mr Grimes Mar 07 '15 at 21:12

0 Answers0