0

assume that login.check() checks for validation of the fields after that I post the data to 'check.php' since it is an ajax request so to wait for the response I have taken a variable called flag(initialized with 'false'). When the response is processed I set the flag as 'true'. But, there is something is wrong with this script because the page freezes. But I cannot debug the script so please help me.

$('.login-form').submit(function(){
   var flag = false , tag;
   if(login.check() === false){
        return false;
   }
    else{
        $.post('check.php',{
            "username":$('#username1').val(),
            "password":$('#password1').val()
            },function(data){
                var obj = JSON.parse(data);
                if(obj.status === false){
                    var server_alert = document.getElementsByClassName('server-alert')[0];
                    server_alert.innerHTML = obj.error;
                    server_alert.className = server_alert.className.replace('display-hide','');
                    tag = false;
                    flag = true;
                }
                else if(obj.status === true){
                    tag = true;
                    flag = false;
                }
        });
    }
    while(flag != true);
    return tag;

})
  • What are you trying to do with this while(flag != true); – Nikhil Aggarwal Jun 20 '15 at 05:29
  • 1
    You cannot loop waiting for something to change in Javascript. You simply can't do that. It's non-preemptive single threaded so as long as your loop is running, the Ajax result can never be processed, thus your loop can never finish (essentially an infinite loop). Instead, you must process the result of the Ajax function inside the `.post()` completion handlers. That's how you use async callbacks in Javascript. – jfriend00 Jun 20 '15 at 05:31
  • thanks, jfriend00 I thought that callbacks work on different threads. Can we do this with XMLHttpRequest.onreadystatechange because events work on different threads. – user3809584 Jun 20 '15 at 05:40
  • All JS in a browser (except webWorkers which aren't in play here) run on the same thread. So your Ajax callback cannot run until the rest of your JS is done executing. See [How does JavaScript handle AJAX responses in the background?](http://stackoverflow.com/questions/7575589/how-does-javascript-handle-ajax-responses-in-the-background/7575649#7575649) for a more detailed description. – jfriend00 Jun 20 '15 at 05:41
  • Your jQuery `$.post()` will just be using `onreadystatechange` internally anyway. JS events do *not* work on different threads. – nnnnnn Jun 20 '15 at 06:01

0 Answers0