0

I need my function to return FALSE if user exists and TRUE if user doesn't exist in database. Here is my function code. Firebug showed me that variable flag stays undefined all the time. How can I fix it ?

function checkLogin(login, n) { 
        var flag;

        jQuery.ajax({
            type: "POST",
            url: "${pageContext.request.contextPath}/checkLogin.ajax",
            data: "login="+login.val(), 

            success: function(response){
                if (response.status == "EMPTY") {
                    alert('Login is free - you can take it');
                    flag = true;
                } 

                if (response.status == "EXISTS") {              
                    alert('Login already exists in Database');
                    login.addClass( "ui-state-error" );
                    updateTips( n );
                    flag = false;
                }

            }
        });

        return flag;
    }
gabriel angelos
  • 349
  • 1
  • 9
  • 23
  • 1
    Where's the amazing canonical duplicate for this question that appears way too often? I want to bookmark it – John Dvorak Mar 05 '13 at 09:09
  • see http://stackoverflow.com/questions/15155607/use-jquery-ajax-dont-have-callback-when-return-true/15156942#15156942 – J.G.Sebring Mar 05 '13 at 09:11

4 Answers4

0

AJAX is asynchronous. Your return statement will occur before the callback code to alter the flag is completed. You need to change your logic so that the function doesn't return a flag, but rather passes it to a callback that you define.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
0

A couple of problems:

  • ajax will work asynchronously, so you can't be sure it will complete (and therefore set flag) before you return the value you're waiting for it to set;
  • and, you don't specify a handler for the error parameter, so if something is going wrong then you won't know about it.
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
0

you cannot return flag.. It will executed directly without considering your ajax call hence until your ajax call is in process, it will return the flag before ajax operation is done. it will not work

You can take help of $.deferred instead

look at it

K D
  • 5,889
  • 1
  • 23
  • 35
-1

Try posting data as data: "login:"+login.val(),

use : instead of =

and also try posting data with '" + + "'

Ketan
  • 36
  • 4