views:

30

answers:

1

I have written a function, which has to check whether a username has been taken or not. Now when I call the function from another function, and alert it's return value:

 alert(checkusernameavailable('justausername')); 

it says 'undefined'. I've searched high and low, but can't find what I'm doing wrong. I guess it should just return the php-echo in check.php, but it doesn't. Here's the function I wrote:

var checkusernameavailable = function(value)  {
    $.ajax({
      url: "check.php",
      type: "POST",
      async: false,
      cache: false,
      data: "username=" + value + "",

      success: function(response) {
        alert(response);
        return response;        
      },
      error: function() {
        alert('ajax error');
      }
    });
  } 

What am I doing wrong?

+1  A: 

AJAX calls are async, which means they only return data after the operation has completed. I.e. the method checkusernameavailable never returns any information (unless you tell it to within that method itself). You need to do the following:

// Just fire and forget the method
checkusernameavailable("userName");

// Change the success function to do any display you require
success: function(response) {
    alert(response);
    $("#SomeDiv").html(response);     
  },

The method fires the AJAX async method that posts to check.php. When the response is received, you then handle that response in function associated with the success callback of $.ajax. You can specify a function directly to that success callback as well:

// Change success to point to a function name
success: foo

// Create a function to handle the response
function foo(response)
{
   // Do something with response
}

EDIT:

As per the OP's comment, you need to change your AJAX call to be synchronous, instead of asynchronous (I've never done a synchronous call like this myself, so this is untested):

var ajaxResponse;

$.ajax({
    async: false, 
    success : function (response)
              {
                  ajaxResponse = response;
              },
    // other properties
});

return ajaxResponse;

Full API listing here.

GenericTypeTea
Thank you for your answer, I understand it. But it doesn's solve my problem. Let me explain what I want a little further. I am firing the function checkusernameavailable from within another function, which fires when my form is submit. So what I'm doing is:if (!checkusernameavailable(username_box.val())) {return false; // don't submit the form// and make some boxes red, unhiding multilingual error messages (Which - btw - means I can't insert the response directly into my html...)}
@user468893 - See my edit. You need to make your Async AJAX call synchronous.
GenericTypeTea
It already was, but that was not the trick :) The return value did the magic. Thanks!