简体   繁体   中英

Submit form with javascript/jquery after php validation

Could someone help me with this problem. I have to submit a form after I checked if the database doesn't contain the inserted email.

PHP code for email control

$email = $_POST['email'];

$sql = "SELECT * FROM sc_user WHERE email='" . $email . "'";
$select = mysql_query($sql);
$row = mysql_num_rows($select);
$conn_object->connection_signout();

if($row > 0)
  echo "exist";
 else
  echo "notexist";

PHP code for inserting new user in database

if (isset($_POST['submit_registration']))
  {
  $sql = "INSERT INTO sc_user (name, surname, email, password) VALUES ('" . $_POST['user_name'] . "',
     '" . $_POST['user_surname'] . "', '" . $_POST['email'] . "', '" . md5($_POST['password']) . "')";
if (mysql_query($sql))
    {
    $conn_object->connection_signout();
    }
header("Location: index.php");
}

Part of the javascript code I have is this.

$(document).ready(function(){
  $("#register_form").submit(function(evReg) {
    evReg.preventDefault();

//other code...

$.post('../PHP/checkMail.php', {'email' : email}, function(data) {
    if(data == 'exist') 
      {
      $('#email_id').val('');
      $('#email_id').attr('placeholder', 'User already registered with this email');
      $('#email_id').addClass('placeholder_red');
      $('#email_id').focus();
      }
    else 
      {
      $(this).submit();
      }
  });
//this.submit();
//other code

If I put "this.submit();" outside "$.Post(...);" block the form will submit corectly, but if is inside it's like it doesn't find the form, I think.
Sorry for the english, I hope you will understand my problem.

I've tried using this

document.getElementById("register_form").submit();

but it doesn't work. I hope I give you all the information you ned.

It doesn't work because you are inside the scope of the callback function of $.post() so $(this) doesn't reference properly to your form, you can try changing your code like this:

$("#register_form").submit(function(evReg) {
     evReg.preventDefault();
     var $this = $(this);
    //other code

and then in your callback function submitting the form using the $this variable

if(data == 'exist') 
  {
  $('#email_id').val('');
  $('#email_id').attr('placeholder', 'User already registered with this email');
  $('#email_id').addClass('placeholder_red');
  $('#email_id').focus();
  }
else 
  {
  $this.submit();
  }

I haven't tested your code, so i cannot be sure it works but different times this worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM