2017-03-24 26 views
0

我在同一页面上有一个登录和注册表单,我使用jQuery隐藏,因此一次只有一个表单处于活动状态。当我注册表单处于活动状态时,请填写电子邮件字段,其中包含与我的PHP if-statement不匹配的电子邮件,然后按提交,页面将刷新并激活登录表单。无法让Ajax以我想要的方式使用PHP

我想让页面执行的是运行PHP脚本,当PHP if语句失败时,它将阻止刷新页面,然后打印位于PHP else语句中的消息。

的代码看起来是这样的:

PHP:

if(isset($_POST['register'])) { 
    $email = strip_tags($_POST['email']); 
    $password = strip_tags($_POST['password']); 
    $request = $_POST['request']; 

    $email = $DBcon->real_escape_string($email); 
    $password = $DBcon->real_escape_string($password); 

    $email = $_POST['email']; 
    $password = $_POST['password']; 

    $hashed_password = password_hash($password, PASSWORD_DEFAULT); 
    $check_email = $DBcon->query("SELECT email FROM members WHERE email='$email'"); 
    $count = $check_email->num_rows; 

    if ($count==0) { 
     if (preg_match('/^[a-z]{6}+[0-9]{2}[email protected]+$/i', $email)) { 
      $query = "INSERT INTO members(email, password) VALUES('$email', '$hashed_password')"; 
      $result = $DBcon->query($query); 
      header("Location: home.php"); 
      die(); 
     } else { 
      echo "You must provide a valid student email!"; 
     } 
    } else{ 
     echo "Email already taken!"; 
    } 
} 
$DBcon->close(); 

的jQuery:

$(document).ready(function() { 

var request = $(this).serialize(); 
$("#registerform").on('submit', function (event) { 
    event.preventDefault(); 

    $.ajax({ 
    type: 'POST', 
    url: 'registration.php', 
    data: request, 
    success: function(){ 
     $(this).submit(); 
     console.log("test"); 
    }, 
    error: function() { 
     event.preventDefault(); 
    alert("fail"); 
    } 
    }); 

    }); 
}); 
+4

将'var request = $(this).serialize();'放入提交函数中。 – DrKey

+0

我试过这个,但是我得到这个错误:“未定义的索引:request in ....”引用我的“$ request = $ _POST ['request'];”在我的PHP。当我运行“print_r($ _ POST);”请求的值实际上正在打印.. – Kristoffer

回答

0

林假设你的代码运行正常,并且您在JavaScript中正常地接收到的数据通过后,然后只有这些改变才能完成。

if ($count==0) { 
     if (preg_match('/^[a-z]{6}+[0-9]{2}[email protected]+$/i', $email)) { 
      $query = "INSERT INTO members(email, password) VALUES('$email', '$hashed_password')"; 
      $result = $DBcon->query($query); 

    if ($result){ 
     header("Location: home.php"); 
     } 
    else{ 
      die("Some error"); 
    } 
      die(); 
     } else { 
      die("You must provide a valid student email!"); 
     } 
    } else{ 
     die("Email already taken!"); 
    } 
+0

现在我不断收到“未定义的索引:请求....”引用我的“$ request = $ _POST ['request'];”在我的PHP。当我运行“print_r($ _ POST);”请求的值实际上正在打印。 – Kristoffer

+0

检查您是否已将表单中的关键字名称用作'请求'。只有当您没有$ _POST [variable]的值时才会显示此错误;所以检查可变部分。另外检查它是否正确传递给php。 –

+0

当我将要被序列化的对象从“this”更改为实际的表单ID“#registerform”时,它部分起作用,它不会从PHP中的else语句(“您必须提供有效的学生电子邮件”)打印出来。但是,然后,在Ajax的错误部分,我得到警报可以工作,但不是防止默认设置。任何提示? – Kristoffer

相关问题