tags:

views:

89

answers:

2

Hello guys,

I have a very limited jQuery experience and I was wondering if you can help me with a function that has to check, with an AJAX request, if an email address exists or not.

Until now I have this piece of code for email checking:

$('input#email').bind('blur', function(){
  $.ajax({
    url: 'ajax/email.php',
    type: 'GET',
    data: 'email=' + $('input#email').val(),
    cache: false,
    success: function(html) {
      if (html == 1) alert('Email exists!');
    } 
  });
});

How can I make a function out of this and use it like this:

if (!email_exists($('input#email').val())) {
   $('#error_email').text('Email exists').show();           
   return false;
}

My PHP code looks like this:

$email = ($_GET['email']) ? $_GET['email'] : $_POST['email'];

$query = "SELECT `id` FROM `users` \n"
       . "WHERE `users`.`email` = '".mysql_real_escape_string($email)."'";     
$result = mysql_query($query); 

if (mysql_num_rows($result) > 0) {  
    echo '1';
} else {
    echo '0';
}

Thank you.

+1  A: 

You've already made it a "function" by attaching it to the blur event of your input. I would just

success: function(html) {
  if (html == 1) 
    $('#error_email').text('Email exists').show();
  else
    $('#error_email').hide();
} 
Ted
I know, but I want to make it a different function.
Psyche
+2  A: 

If you really must have an answer returned from the function synchronously, you can use a synchronous XMLHttpRequest instead of the normal asynchronous one (the ‘A’ in AJAX):

function email_exists(email) {
    var result= null;
    $.ajax({
        url: 'ajax/email.php',
        data: {email: email},
        cache: false,
        async: false, // boo!
        success: function(data) {
            result= data;
        }
    });
    return result=='1';
}

However this is strongly discouraged as it will make the browser hang up whilst it is waiting for the answer, which is quite user-unfriendly.

(nb: also, pass an object to data to let jQuery cope with the formatting for you. Otherwise, you would need to do 'email='+encodeURIComponent(email) explicitly.)

You can't have a function that synchronously returns a value from an asynchronous action, or vice versa (you would need threads or co-routines to do that, and JavaScript has neither). Instead, embrace asynchronous programming and have the result returned to a passed-in callback:

$('#email').bind('change', function() {
    check_email($('#email').val(), function(exists) {
        if (exists)
            $('#error_email').text('Email exists').show();
    });
});

function check_email(email, callback) {
    $.ajax({
        url: 'ajax/email.php',
        data: {email: email},
        cache: false,
        success: function(data) {
            callback(data=='1');
        }
    });
}
bobince
I understand, thank you.
Psyche