php 到 AJAX 表单提交

Posted

技术标签:

【中文标题】php 到 AJAX 表单提交【英文标题】:php to AJAX form submission 【发布时间】:2014-02-14 18:54:43 【问题描述】:

AJAX 的新手我得到了这个代码,请帮忙,我的代码会继续进入 sec_reg.php 页面,即使密码不匹配,或者即使表单有效,我也希望用户留在当前页面上如果他提交表格。这是我的代码

这是我的表格

    <h4>ADD ANOTHER ADMIN</h4>
     <form action="sec_reg.php" method="post" name="registration_form">
     <br>
     <p>

     <strong>Email</strong>
     <br>
     <br>
    <input class="acc_input" type="text" id="email" name="email"placeholder="Email">

    </p>
    <br>
    <p>
   <strong>        Password</strong>
    <br>
    <br>
    <input class="acc_input" type="password" name="password" id="password" placeholder="Password">
    <br /><br />
    <strong>        Confirm Password</strong>
    <br>
    <br>
    <input class="acc_input" type="password" name="cpassword" id="cpassword" placeholder="Confirm Password">

    <input type="hidden" name="p" id="p" value="">
    <br>

   </p>
    <button type="submit" class="btnsubmit" onclick="formhash(this.form,  
 this.form.password, this.form.p);" ><strong>Register</strong></button>

    </form>

这里是forhash的脚本(密码需要在发送之前进行哈希处理)

<script src="sha512.js"></script>
<script>
function formhash (form, password)

 var pass1 = document.getElementById("password").value;
var pass2 = document.getElementById("cpassword").value;
var ok = true;
if (password != cpassword) 
    //alert("Passwords Do not match");
    document.getElementById("password").style.borderColor = "#E34234";
    document.getElementById("cpassword").style.borderColor = "#E34234";
    ok = false;


else 


var p = document.createElement("input");    
form.appendChild(p);
p.name="p";
p.type="hidden";
p.value=hex_sha512(password.value);
password.value="";
form.submit();

 
  
 </script>

这是我的 sec_reg.php

<?php
// Include database connection and functions here.
include '../Connections/mabini150_Conn.php';
if (isset($_POST['p']))

include 'login_Function.php';
 // The hashed password from the form
$password = $_POST['p'];
// Create a random salt
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
// Create salted password (Careful with the chilli)
$password = hash('sha512', $password.$random_salt);
$username='nousername';
$email = $_POST['email'];
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)"))

$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
// Execute the prepared query.
$insert_stmt->execute();

【问题讨论】:

【参考方案1】:

调用formhash()后需要返回false;在您的 onclick 属性中。

<button type="submit" class="btnsubmit"
    onclick="formhash(this.form, this.form.password, this.form.p); return false;" ><strong>Register</strong></button>

否则按钮无论如何都会提交。

【讨论】:

以上是关于php 到 AJAX 表单提交的主要内容,如果未能解决你的问题,请参考以下文章

PHP symfony 4 ajax 表单提交

表单提交(同步提交)和AJAX提交(异步提交)

PHP + jQuery + Ajax 表单提交 - 同一页面返回结果

PHP表单提交失败,如何返回原值?

使用 AJAX 向 PHP Web 服务提交基本表单数据

使用ajax将表单提交给php而不刷新页面