0

I'm trying to add remote method for check login availability to jquery validation. I have read other questions, but it don't helped me... It's not working. I do not know where I was wrong

$('#contact-form').validate({        
    rules: {
      login: {
        required: true,     
        remote: {
            url: "user_availability.php",
            type: "post",
            data:
                  {
                      login: function()
                      {
                          return $('#contact-form :input[name="login"]').val();
                      }
                  }
        }           
      }       
    },
     messages:{
         login:{
         required: "Please enter your login.",
         remote: jQuery.validator.format("{0} is already taken.")
         }            
    }

});

File user_availability.php :

<?php       
    $existing_users=array('admin','mike','jason'); 

    $user_name=$_POST['user_name'];

    if (in_array($user_name, $existing_users))
    {       
        echo "false"; //already registered
    } 
    else
    {       
         echo "true";  //user name is available
    }
?>
Sparky
  • 98,165
  • 25
  • 199
  • 285
T_E_M_A
  • 560
  • 1
  • 11
  • 28

1 Answers1

4

This is because in jQuery validate you take the field name as "login", whereas in PHP file you take the user_name.. both are different.

Please take the following code and let me know...

<script>
$(function(){
    $('#contact-form').validate({        
    rules: {
      user_name: {
        required: true,     
        remote: {
            url: "user_availability.php",
            type: "post",
            data:
                  {
                      login: function()
                      {
                          return $('#contact-form :input[name="user_name"]').val();
                      }
                  }
        }           
      }       
    },
     messages:{
        user_name:{
         required: "Please enter your login.",
         remote: jQuery.validator.format("{0} is already taken.")
         }            
    }
});
});
</script>
TECHNOMAN
  • 361
  • 1
  • 9
  • You have the correct answer. However note that the OP does not need the `data` option under `remote` since, by default, the value of the `user_name` field is already being sent. `data` option is only for sending `additional` data. – Sparky Dec 17 '14 at 16:29
  • Yes, it was in this. And I still missed ode comma( Now it works, thanks. – T_E_M_A Dec 17 '14 at 21:15
  • why I always get email@domain.com is already taken even if the email is not exist? – Abaij Jan 05 '18 at 09:33