5

I am attempting to validate an email address if it already exists in a table, but this isn't working.

Here's my code:

<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$('#Submit').click(function() {
    var emailVal = $('#email').val(); // assuming this is a input text field
    $.post('checkemail.php', {'email' : emailVal}, function(data) {
        alert(data);
    });
});
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="view.php">
  <p>
    <input type="text" name="email" id="email" />
  </p>
  <p>
     <input type="submit" name="Submit" id="Submit" value="Submit" />
  </p>
</form>
</body></html>

When the Submit button is clicked, it should validate first using the jQuery and call the checkemail.php file as shown below:

<?php
include("../includes/db.php");

$sql = "SELECT email FROM lf_clients WHERE email = " .$_POST['email'];
$select = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($select);

if (mysqli_num_rows > 0) {
    echo "The email already exists.";
}
?>

However, when I click the submit button it goes to view.php instead of checkemail.php. Before it redirects to view.php, it should check first if the email already exists or not. If the email already exists, then it should not redirect to view.php.

5 Answers 5

10
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){ //newly added 
$('#Submit').click(function() {alert('in');
    var emailVal = $('#email').val(); // assuming this is a input text field
    $.post('checkemail.php', {'email' : emailVal}, function(data) {
        if(data=='exist') return false;
        else $('#form1').submit();
    });
});});
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="view.php">
  <p>
    <input type="text" name="email" id="email" />
  </p>
  <p>
    <input type="button" name="Submit" id="Submit" value="Submit" />
  </p>
</form>
</body>
</html>

php Code

<?php
include("../includes/db.php");

$sql = "SELECT email FROM lf_clients WHERE email = " .$_POST['email'];
$select = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($select);

if (mysqli_num_rows > 0) {
    echo "exist";
}else echo 'notexist';
?>
Sign up to request clarification or add additional context in comments.

7 Comments

i tried this, but still doesn't work. even if I entered an email in the email field that is already existed in the table, it will still redirect to view.php.
my bad. this code works. the problem is w/ my php code. thank you
by the way how can I display the message in the body like: <p>Email already exists</p>?
in script if(data=='exist'){ $('#submit').after('<div class="error">Email already exists</div>')} add this code.
thanks, when i integrate the code to my final script it seems that it conflicts w/ my other javascript code. because under the form tag i have the following code: <form id="form1" name="form1" method="post" action="view.php" onsubmit="return btnSubmitPD_OnClick()"> here's the code in my btnSubmitPD_OnClick() function btnSubmitPD_OnClick(){ frmReg = document.getElementById("form1"); if(frmReg.email.value == ""){ alert("Email can not be empty! Please re-enter."); frmReg.email.focus(); return false; return true; } </script>
|
1

Best practice for these kind of stuff is to use Jquery remote validate method.

  $("#myform").validate({
      rules: {
        email: {
          required: true,
          email: true,
          remote: "check-email.php"
        }
      },
      messages:{
         email:'Email address exists.'
     }
    });

In PHP file, you can do what @Sachyn has mentioned.

Comments

0

I suspect you have to abort the standard action of the submit button. You also might have to change action from click to submit, can't test it right now though.

$('#Submit').submit(function(e) {
    var usernameVal = $('#email').val(); // assuming this is a input text field
    $.post('checkemail.php', {'email' : emailVal}, function(data) {
        alert('data');
    });
    e.preventDefault(); // <------
});

Comments

0

You can do the following

  1. In your PHP file -

     if (mysqli_num_rows > 0) {
          echo "0"; // email exists
     else
          echo "1"; // email doesn't exists
     return;
    
  2. In your HTML file, use <input type="button" instead of <input type="submit"

And in the JavaScript

$.post('checkemail.php', {'email' : emailVal}, function(data) {
   if (data == 1)
   { 
       $("#form1").submit();
   }
   else
   {
        alert("Email already exists");
        return false;
   }
});

Comments

0

If you prefer to check using JQuery you can do it as follows

$('document').ready(function(){
 var username_state = false;
 var email_state = false;
 $('#username').on('blur', function(){
  var username = $('#username').val();
  if (username == '') {
    username_state = false;
    return;
  }
  $.ajax({
    url: 'register.php',
    type: 'post',
    data: {
        'username_check' : 1,
        'username' : username,
    },
    success: function(response){
      if (response == 'taken' ) {
        username_state = false;
        $('#username').parent().removeClass();
        $('#username').parent().addClass("form_error");
        $('#username').siblings("span").text('Sorry... Username already taken');
      }else if (response == 'not_taken') {
        username_state = true;
        $('#username').parent().removeClass();
        $('#username').parent().addClass("form_success");
        $('#username').siblings("span").text('Username available');
      }
    }
  });
 });        
  $('#email').on('blur', function(){
    var email = $('#email').val();
    if (email == '') {
        email_state = false;
        return;
    }
    $.ajax({
      url: 'register.php',
      type: 'post',
      data: {
        'email_check' : 1,
        'email' : email,
      },
      success: function(response){
        if (response == 'taken' ) {
          email_state = false;
          $('#email').parent().removeClass();
          $('#email').parent().addClass("form_error");
          $('#email').siblings("span").text('Sorry... Email already taken');
        }else if (response == 'not_taken') {
          email_state = true;
          $('#email').parent().removeClass();
          $('#email').parent().addClass("form_success");
          $('#email').siblings("span").text('Email available');
        }
      }
    });
 });

 $('#reg_btn').on('click', function(){
    var username = $('#username').val();
    var email = $('#email').val();
    var password = $('#password').val();
    if (username_state == false || email_state == false) {
      $('#error_msg').text('Fix the errors in the form first');
    }else{
      // proceed with form submission
      $.ajax({
        url: 'register.php',
        type: 'post',
        data: {
            'save' : 1,
            'email' : email,
            'username' : username,
            'password' : password,
        },
        success: function(response){
            alert('user saved');
            $('#username').val('');
            $('#email').val('');
            $('#password').val('');
        }
      });
    }
 });
});
body {
  background: #A9D9C3;
}
#register_form h1 {
  text-align: center;
}
#register_form {
  width: 37%;
  margin: 100px auto;
  padding-bottom: 30px;
  border: 1px solid #918274;
  border-radius: 5px;
  background: white;
}
#register_form input {
  width: 80%;
  height: 35px;
  margin: 5px 10%;
  font-size: 1.1em;
  padding: 4px;
  font-size: .9em;
}
#reg_btn {
  height: 35px;
  width: 80%;
  margin: 5px 10%;
  color: white;
  background: #3B5998;
  border: none;
  border-radius: 5px;
}
/*Styling for errors on form*/
.form_error span {
  width: 80%;
  height: 35px;
  margin: 3px 10%;
  font-size: 1.1em;
  color: #D83D5A;
}
.form_error input {
  border: 1px solid #D83D5A;
}

/*Styling in case no errors on form*/
.form_success span {
  width: 80%;
  height: 35px;
  margin: 3px 10%;
  font-size: 1.1em;
  color: green;
}
.form_success input {
  border: 1px solid green;
}
#error_msg {
  color: red;
  text-align: center;
  margin: 10px auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<html>
<head>
  <title>Register</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
 <form id="register_form">
      <h1>Register</h1>
      <div id="error_msg"></div>
      <div>
        <input type="text" name="username" placeholder="Username" id="username" >
        <span></span>
      </div>
      <div>
        <input type="email" name="email" placeholder="Email" id="email">
        <span></span>
      </div>
      <div>
       <input type="password" name="password" placeholder="Password" id="password">
      </div>
      <div>
        <button type="button" name="register" id="reg_btn">Register</button>
      </div>
    </form>
</body>
</html>
<!-- scripts -->
<script src="script.js"></script>

For this code to fully function, it needs its own backend. But by looking through this code, you can understand the basic flow of how to check if any field does exist in the database. This is the main code that does the main job.

  $('#email').on('blur', function(){
var email = $('#email').val();
if (email == '') {
    email_state = false;
    return;
}
$.ajax({
  url: 'register.php',
  type: 'post',
  data: {
    'email_check' : 1,
    'email' : email,
  },
  success: function(response){
    if (response == 'taken' ) {
      email_state = false;
      $('#email').parent().removeClass();
      $('#email').parent().addClass("form_error");
      $('#email').siblings("span").text('Sorry... Email already taken');
    }else if (response == 'not_taken') {
      email_state = true;
      $('#email').parent().removeClass();
      $('#email').parent().addClass("form_success");
      $('#email').siblings("span").text('Email available');
    }
  }
});

});

You can get the backend from the Source

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.