0

i am trying to check if an email exists in the db but the function doesn't return a value.

This is the code:

function checkemail(email)
{
    var returnVal = "";
    if (email.indexOf("@") != -1 && email.indexOf(".") != -1)
    {
        $.post( "registreren.php?email=" + email, function( response ) {
            if(response == 1) { returnVal = 1; }
            if(response == 2) { returnVal = 2; }
        });
    }
    else
    {
        returnVal = 3;
    }//email

    return returnVal;

}

EDIT: email is send as a string

naknak12
  • 41
  • 10

2 Answers2

0

Can you use something simple like below

$.ajax({
        url: 'registreren.php',
        type: 'post',
        dataType: "json",
        data: {'email': email},
        success: function (response) {
            if (response == 1)
            {
               returnVal = 1; 
            }
            else
            {
               returnVal = 3; 
            }
        }
    });

instead of

$.post( "registreren.php?email=" + email, function( response ) {
            if(response == 1) { returnVal = 1; }
            if(response == 2) { returnVal = 2; }
    });
Nitin Sali
  • 339
  • 1
  • 9
0

I short, You can not return values from ajax calls as it is asynchronous by nature, the statement return value executes before

To address such cases, use callback, a function accepted as argument and which is executed when response is been received (when asynchronous action is completed).

Try this:

function checkemail(email, callback) {
  var returnVal = "";
  if (email.indexOf("@") != -1 && email.indexOf(".") != -1) {
    $.post("registreren.php?email=" + email, function(response) {
      callback(response);
    });
  } else {
    callback(3);
  }
}
checkemail('abc@xyz.com', function(val) {
  alert(val);
});

checkemail('INVALID_EMAIL', function(val) {
  alert(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Rayon
  • 36,219
  • 4
  • 49
  • 76