StevieD
StevieD

Reputation: 7433

Unable to use callback to get response from ajax call

I'm using the jQuery Validator plugin to try to check whether an email address getting entered into the form is unique after an ajax call which passes the email to a script which checks to see if the email is already in the database. I'm using a callback function to try to get the results of the ajax query but the function always returns undefined. I'm not sure what I'm doing wrong. Here is the code:

jQuery.validator.addMethod("unique", function () {
    function foo(callback) {
        $.ajax({
            type: 'POST',
            async: true,
            url: '/form_processor',
            data: 'action=email_validate&email=' + $("#email").val(),
            success: callback
        });
    }
    var return_value = foo(function (result) {

        if (result !== 'g') {
            return false;
        } else {
            return true;
        }
    });
    alert(return_value);
}, "Email address taken. Choose another.");

Upvotes: 0

Views: 51

Answers (1)

Jomy Joseph
Jomy Joseph

Reputation: 331

If you are using jquery validator, in built method is their to validate, So your validate code will like,

$(document).ready(function(){
   $( "#myform" ).validate({
      rules: {
        email: {
          required: true,
          email: true,
          remote: {
            url: "form_processor",
            type: "post",
            data: {
              email: function() {
                return $( "#email" ).val();
              }
            }
          }
        }
      },
    messages:
         {
         email:
             {
                required: "Please enter your email address.",
                remote: "Email already taken"
             }
         }
    });
})

In server side you have to return (print) true or false code will be (if you are using php)

<?php 
$email =  $_POST['email'];
    $query = "SELECT ID FROM users WHERE user_email = "$email" LIMIT 1;";
    $results = $mysqli->query($query);
    if($results->num_rows == 0)
    {
        echo "true";  //good to register
    }
    else
    {
        echo "false"; //already registered
    }
}
else
{
    echo "false"; //invalid post var
}

?>

Upvotes: 1

Related Questions