gpt4 book ai didi

php - Ajax 代码将表单数据发送到 PHP 服务器进行验证

转载 作者:行者123 更新时间:2023-12-01 06:57:51 26 4
gpt4 key购买 nike

我很难将此 AJAX 代码实现到我的表单中,以便页面不需要重新加载但仍会执行服务器端验证。我是 AJAX 和 PHP 的新手,所以我正在研究几个表单模板,但我已经为此工作了几个小时,但我不明白为什么它不起作用。任何帮助将不胜感激。

以下是 HTML 代码的一部分:

<div id="popupContact">
<form id="formElem" name="formElem" action="" method="post">
<fieldset class="step">
<legend>Personal Details</legend>
<p>
<label for="firstname">First Name</label><em>*</em>
<input id="firstname" name="firstname" />
</p>
<p>
<label for="lastname">Last Name</label><em>*</em>
<input id="lastname" name="lastname" />
</p>
<p>* fields are required</p>
</fieldset>
<fieldset class="step">
<legend>Confirm</legend>
<p>Before you submit your information, please ensure that each step
below has this <img src="../img/global/checked.png" alt="Complete" >
above them. If there is a step that has this
<img src="../img/global/error.png" alt="Error" >, please click on that tab
and review the information to ensure it is correct and complete. Thank you.</p>
<p>
<label for="human">Please Type: "Something"</label><em>*</em>
<input id="human" name="human" />
</p>
<p class="submit">
<button id="registerButton" type="submit">Submit</button>
</p>
</fieldset>
</form>
</div>

这是 JAVAScript 代码:

$(function() {
var form = $("#formElem");
var fname = $("#firstname");
var lname = $("#lastname");
var address = $("#streetaddress");
var city = $("#city");
var state = $("#state");
var phone = $('#phone');
var email = $('#email');
var insurance = $('#insurance');
var license = $('#license');
var human = $('#human');
$('#registerButton').bind('click',function(){
if($('#formElem').data('errors')){
alert('Please correct the errors in the Form');
return false;
}
else {
var dataString = 'fname='+$('#firstname').val()+'&lname='+$('#lastname').val()+'&address='+$('#streetaddress'.val())+'&city='+$('#city')+'&state='+$('#state').val()+'&phone='+$('#phone').val()+'&email='+$('#email').val()+'&insurance='+$('#insurance').val()+'&license='+$('#license').val()+'&human='+$('#human').val();
$.ajax({
type: "POST",
url: "js/validation.php",
data: dataString,
async: false,
success: function() {
$('#popupContact').html("<div id='message'></div>");
$('#message').html("<h2>Inquiry Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='..img/global/check.png' />");
});
}
});
return false;
}
});

这是 PHP 代码:

<?php
if(isset($_POST['email'])) {
$email_to = "somebody@somewhere.com";
$email_subject = "Inquiry";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}

// validation expected data exists
if(!isset($_POST['firstname']) ||
!isset($_POST['lastname']) ||
!isset($_POST['email']) ||
!isset($_POST['phone']) ||
!isset($_POST['streetaddress']) ||
!isset($_POST['city']) ||
!isset($_POST['state']) ||
!isset($_POST['insurance']) ||
!isset($_POST['license']) ||
!isset($_POST['human'])){
died('We are sorry, but there appears to be a problem with the form you submitted.');
}

$firstname = $_POST['firstname']; // required
$lastname = $_POST['lastname']; // required
$emailfrom = $_POST['email']; // required
$phone = $_POST['phone']; // required
$address = $_POST['streetaddress']; //required
$city = $_POST['city']; //required
$state = $_POST['state']; //required
$insurance = $_POST['insurance']; //required
$license = $_POST['license']; //required
$human = $_POST['human']; //required

$error_message = "";
$email_exp = '/^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/';
if(!preg_match($email_exp,$emailfrom)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}

$email_message = "Form details below.\n\n";

function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($firstname)."\n";
$email_message .= "Last Name: ".clean_string($lastname)."\n";
$email_message .= "Email: ".clean_string($emailfrom)."\n";
$email_message .= "Telephone: ".clean_string($phone)."\n";
$email_message .= "Address: \n".clean_string($address)."\n";
$email_message .= "".clean_string($city).", ";
$email_message .= "".clean_string($state)."\n";
$email_message .= "Have Insurance: ".clean_string($insurance)."\n";
$email_message .= "Have License: ".clean_string($license)."\n";


// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>

<!-- include your own success html here -->

Thank you for contacting us. We will be in touch with you very soon.

<?php
}
?>

我省略了大部分实际验证代码部分,所以我知道您看到的并不完整。我不明白的是,如果没有 AJAX 部分,表单验证在客户端和服务器端都可以正常工作,但是当我添加 AJAX 时,有些东西无法连接。感谢您提前提供的帮助。

编辑有人对我的代码哪里出了问题有建议吗?

编辑好的,如果我将 js/validation.php 放在表单的 action="" 标记中并禁用代码的 AJAX 部分,那么验证就可以正常工作,但我被转发到一个带有确认码的空白页面。这是否说明了这个问题?真的,任何帮助都是值得赞赏的。我尝试使用评论中给出的提示,但由于某种原因没有任何反应。看起来我的页面已刷新,但没有确认消息或任何内容。我完全迷失了。

最佳答案

你的想法并不遥远,但我想我会以稍微不那么激进的方式来攻击这个问题。

  1. 从表单开始,我只需将其设为带有 ID 的表单,并将提交按钮放在表单标签之外。为什么?因为表单内的按钮可能会产生一些不良影响(例如提交到神奇的黑洞)更少的代码 = 快乐的开发人员。
  2. 我会使用点击处理程序捕获按钮上的点击。所以:

    $('#registerButton').click(function(){ 在这里做你的ajax});

  3. 我最初会通过前端验证来捕获错误,因为它可以节省服务器点击次数,并且从 UI 的角度来看更令人愉快。它也更快......不,不能完全依赖它,因为任何有能力的人都可以覆盖它,但这是一个很好的第一步。我个人最喜欢的是here

  4. 在点击操作中,我会使用ajax(就像您在 示例)将表单提交给您的脚本进行验证。 序列化您的表单以将其发送:

        $.ajax({
    type: "POST",
    url: "js/validation.php",
    data: $('#formElem').serialize(),
    ...

    我会让脚本返回一个带有结果案例的 json 字符串(真/假)和支持该情况的数据(例如成功,以及错误情况的数组)所以,你是与上面的 ajax 调用完全正确,但返回数据在我的示例中输入 json (不是 dataString)并添加一个 var这成功后括号(让我们使用 returndata 作为示例)然后,在您的成功回调,返回的数据将作为returndata.field(将字段更改为等于变量名json 字符串)如果不起作用,请检查输出 jsonlint.com

  5. 在步骤 4 成功调用 ajax 时,设置两种情况(if/else)。如果您的结果情况属实,请让他们继续并按照您的 UI 指示指示成功。如果结果情况为 false,则迭代错误情况数组以通知用户每个相应的问题。

你就快到了。如果这是您第一次使用 jQuery AJAX,我真的印象深刻!

关于php - Ajax 代码将表单数据发送到 PHP 服务器进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7101694/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com