Hussam_Cheema
Hussam_Cheema

Reputation: 19

Email Validation is not working in jQuery

Guys i want to validate email address in php file "validate.php". But its not working. I am not getting any response back from "validate.php" file.

jQuery Code:

function validate_email(email){

         $.post('validate.php', {email:email}, function(data){

               $('msg').text(data);

           });
}

$('#input').focusin(function(){ 
  if($('#input').val() === ''){
     $('#msg').text("Enter Valid Email Address");
  }
  else{
       validate_email($('#input').val());
  }       
  }).blur(function(){ 
            $('#msg').text("");
}).keyup(function(){
            validate_email($('#input').val());
      });

"validate.php" code:

<?php
if(isset($_POST['email'])){

   $email = $_POST['email']; 

   if(!empty($email)){
   if(filter_var($email, FILTER_VALIDATE_EMAIL) === false)
          echo 'Email Address is not Valid, Enter a Valid Email Address.';
   else
          echo 'Email is valid. Mubarak Ho!';

   }
  }
?>

Upvotes: 1

Views: 75

Answers (1)

Dinh Phong
Dinh Phong

Reputation: 596

Check the error log because your code work well on my server

This is my code test

HTML Part

<input id="email" type="email" value="[email protected]">
<button>Submit</button>

<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>

<script>

$(document).on('click', 'button', function() {
    var email = $('#email').val();
    console.log(email);
    $.post('validate.php', {email:email}, function(data){
       console.log(data);
    });
})

</script>

PHP Part

if(isset($_POST['email'])){

   $email = $_POST['email']; 

   if(!empty($email)){
   if(filter_var($email, FILTER_VALIDATE_EMAIL) === false)
          echo 'Email Address is not Valid, Enter a Valid Email Address.';
   else
          echo 'Email is valid. Mubarak Ho!';

   }
}

My advice:

  • At $('msg').text(data); it should be $('#msg').text(data);

  • F12 check error log of javascript

  • Check php path on ajax by f12 -> network -> xhr and check status (if you use chrome)

  • if status == 200 (it mean OK) click to validate.php to check response from PHP file

  • don't forget to feedback if you fixed your bug it can help another guy have same bug with you

Upvotes: 1

Related Questions