0

I am trying to validate if an email entered is present in the database or not and based on this result I execute a code. For this I am calling a Javascript function which calls ajax jquery method to a php page which checks id the email entered is present in database. The code used is :

function validateEmail()
 { var username= document.getElementByName("email").value;
 alert("Username is"+ username);
 $.ajax({
            type: "POST",
            url: "emailCheck1.php",
            data: "username="+username,
            success: function(result){
                            if(result=="checked"){
                              return true;
                              }
                             else  
                             {
                              document.getElementById("errorEmail").style.display="inline";
                               return false;
                              } } 
          error: function(xhr){
                    alert("An error occured: " + xhr.status + " " + xhr.statusText);
                }
       });

But the problem is the function returns the value before ajax method completes. So the return value is not correct. How can i make the function not return any value until ajax method completes and based on the return value of ajax method i return the required value... Any help will be highly appreciated...

  • 1
    This is an understandable point of confusion if you're new to asynchronous programming, but this question has been asked hundreds of times on SO. Please search around a little for existing explanations. – jmar777 Jul 27 '15 at 16:09
  • It's often difficult to find a solution to a problem when what you are asking for is impossible. – Kevin B Jul 27 '15 at 16:10

1 Answers1

0

You need to use a callback to process the value once the ajax is finished, or make query synchronous (which is probably the wrong thing.)

You might look into function currying to specify your callback, if you want to set a parameter on the method.

See here

function partial(fn) {
        // A reference to the Array#slice method.
        var slice = Array.prototype.slice;

        // Convert arguments object to an array, removing the first argument.
        var args = slice.call(arguments, 1);

        return function() {
                // Invoke the originally-specified function, passing in all originally-
                // specified arguments, followed by any just-specified arguments.
                return fn.apply(this, args.concat(slice.call(arguments, 0)));
        }

function doRequest()
{
  callback = partial(doSomething, "Test Value");
  $.post('action', {json_arg: "Test Arg"}, callback);
}
mikeb
  • 10,578
  • 7
  • 62
  • 120