-1

I have the following function

function checkIfUserExist(userName){
    $.ajax({
        type : "POST",
        url : "/test/checkUserName/",
        data : "userName=" + userName,
        success : function(data) {
            return data;

        }
    });

}

I am trying to call it from another function

$('#userName').blur(function() {
    alert ( checkIfUserExist($('#userName').val()) );
}

every time i am getting undefined in the alert box. but it should show me the return value in the alert box.

how to fix this??

LynAs
  • 6,407
  • 14
  • 48
  • 83

4 Answers4

2

you cannot return value from ajax call like this. Because ajax is asynchronous process, it will not wait for the success event to happen. If you want to do so, you should try synchronous ajax. something like this

function checkIfUserExist() {
return $.ajax({
    type: "POST",
    url: "/test/checkUserName/",
    async: false
}).responseText;
}

But it is not a good thing to do. It will freeze the browser as well. The good thing you can do is to catch the Success event of ajax and do thing accordingly

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
1

Thats correct behavior, because ajax is async.

To reach your goal you need Jquery.when

$('#userName').blur(function() {
    $.when( 
        checkIfUserExist($('#userName').val())
    )
    .then(function( data ) {
        alert( data );
    });
});
Evgeniy
  • 2,915
  • 3
  • 21
  • 35
-1

Don't return the value from the ajax, since this is an asynchronous call, your alert will be called before the success and the result will always be undefined

alert the output with in your success callback.

function checkIfUserExist(userName){
    $.ajax({
        type : "POST",
        url : "/test/checkUserName/",
        data : "userName=" + userName,
        success : function(data) {
            alert( data );

        }
    });

}

and just call the function here

$('#userName').blur(function() {
    checkIfUserExist($('#userName').val());
}
zzlalani
  • 22,960
  • 16
  • 44
  • 73
-1

Shouldn't the data be in json format?

data: { "userName": userName }

Also, consider using the "done" function instead of success. That should help with the asynchronous nature of the call.

Brian Anderson
  • 621
  • 7
  • 22