gpt4 book ai didi

javascript - AJAX、JSON、PHP 联系表单、event.preventDefault 不起作用且数据未发送到电子邮件

转载 作者:行者123 更新时间:2023-11-28 07:17:12 25 4
gpt4 key购买 nike

我正在尝试设置我的联系表单以使用 json 和 ajax,将所有表单数据提交到我的电子邮件并显示包含此人姓名的成功消息,但每次我提交表单时,event.preventDefault 都会这样做不起作用,它显示我的 contact.php 页面(我用来处理数据并且是空白的)。这是 3 个文件。

HTML

    <form id="form" action="contact.php" method="POST">
<input data-name id="name" type="text" name="name" placeholder=" name" required="required"><br>
<input data-email id="email" type="email" name="email" placeholder=" email" required="required"><br>
<select data-projectType id="projectType" name="projectType" required="required">
<option value="" disabled selected>let's talk about</option>
<option value="brand">branding</option>
<option value="web">web design</option>
<option value="app">app design</option>
<option value="print">print design</option>
<option value="dev">development</option>
<option value="multi">multiple services</option>
<option value="hello">just saying hello!</option>
</select>
<br>
<label for="budget"></label>
<select data-budget id="budget" name="budget" required="required">
<option value="" disabled selected>project budget</option>
<option value="none">none</option>
<option value="> $100">less than $100</option>
<option value="$100-$400">$100 - $400</option>
<option value="$400-$700">$400 - $700</option>
<option value="$700-$100">$700 - $1000</option>
<option value="Negotiate">let's negotiate</option>
<option value="IDK">i don't know</option>
</select>
<br>
<input data-details id="details" type="text" name="details" placeholder=" project details" required="required"><br>
<div class=".grid_4">


<input type="submit" input class="MainCTAContact" input value="DROP ME A LINE"></input>

</form>
PHP

$name = $_POST['name'];
$email = $_POST['email'];
$projectType = $_POST['projectType'];
$budget = $_POST['budget'];
$details =$_POST['details'];
//email address settings
$to = "heathersheridanodesk@yahoo.com";
$headers = "From: $email";
$subject= "I'd like to discuss $projectType";
$message = "Name: $name\nEmail: $email\nProject Type: $projectType\nBudget: $budget\nDetails: $details";
if ( $name == "")
{
echo 'Please tell me your name.';
$result = "Please tell me your name.";
}
else if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", $email))
{
echo 'Please enter a valid email address.';
$result = "Please enter a valid email address.";
}
else if( $projectType == "")
{
echo 'Please select project type';
$result = "Please select project type";
}
else if( $budget == "")
{
echo 'Please select your budget.';
$result = "Please select your budget.";
}
else if ( strlen($details) < 10 )
{
echo ' Please write at least 10 characters.';
$result = "Please write at least 10 characters.";
}
else
{
mail($to, $subject, $message, $headers);
}
}
?>

JS

$(document).ready(function() {
$('#form').submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax( {
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: form.serialize(),
url: "contact.php",
success: function(result) {
form.remove();
var msg = $("<p></p>");
msg.append("Thank you" + data["name"] + ", I'll be in touch soon.")
$('.sent').html(msg).fadeIn();
},
});

我该如何完成这项工作?

最佳答案

好吧,我花时间重新格式化了您的内容,并在代码注释中做了一些解释,希望这对您有所帮助,但您绝对应该查看有关 AJAX 和表单处理的 Web 教程。

表格

 <form id="form" action="contact.php" method="POST">
<input id="name" type="text" name="name" placeholder=" name" required><br>
<input id="email" type="email" name="email" placeholder=" email" required><br>
<select id="projectType" name="projectType" required>
<option value="" selected>let's talk about</option>
<option value="brand">branding</option>
<option value="web">web design</option>
<option value="app">app design</option>
<option value="print">print design</option>
<option value="dev">development</option>
<option value="multi">multiple services</option>
<option value="hello">just saying hello!</option>
</select>
<br>
<label for="budget"></label>
<select id="budget" name="budget" required="required">
<option value="" selected>project budget</option>
<option value="none">none</option>
<option value="> $100">less than $100</option>
<option value="$100-$400">$100 - $400</option>
<option value="$400-$700">$400 - $700</option>
<option value="$700-$100">$700 - $1000</option>
<option value="Negotiate">let's negotiate</option>
<option value="IDK">i don't know</option>
</select>
<br>
<textarea id='details' rows='5'><textarea><br>
<button type='submit' class='MainCTAContact'>Drop me a line</button>
</form>

JavaScript

$(document).ready(function() {
$('#form').submit(function(e) {
e.preventDefault();
//create a new object here
var data = {
name : $('#name', this).val(),
email : $('#email', this).val(),
projectType : $('#projectType', this).val(),
budget : $('#budget', this).val(),
details : $('#details', this).val()
};


$.ajax({
type: 'POST',
dataType: 'json',
data: data,
url: "/contact.php",
success: function(data) {
if(!data.errors){
$('#errors').hide();
$('#form')[0].reset(); //add this just to clear out the user submitted data
$('#form').hthml(data.message)); //rather than remove this just sets its visibility to none. Remove complete destroys the element which might not be desierable in all cases
}else{
$('#form').before('<p id='errors' style='color: #ff0000;'>'+data.errorMessage+'</p>');
}
}
});
});
});

最后是你的 PHP

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$projectType = $_POST['projectType'];
$budget = $_POST['budget'];
$details =$_POST['details'];

//add in a blank error message the error count, and the return array
$errors = 0;
$errorMessage = "";
$resposne = array();
$response['errors'] = false; //initialize the response boolean



if (empty($name)){
$errorMessage .= 'Please tell me your name<br>';
}
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", $email)){
$errorMessage .= 'Please enter a valid email address<br>';
}
if(empty($projectType)){
$errorMessage .= 'Please select project type<br>';
}
if(empty($budget)){
$errorMessage .= 'Please select your budget.<br>';
}
if(empty($details) || strlen($details) < 10){
$errorMessage .= "Please make sure your message is at least 10 characters long<br>";
}

if(!empty($errorMessage)){
$response['errors'] = true;
$response['errorMessage'] = "There were some errors when processing your form <br> $errorMessage";
}else{
$to = "heathersheridanodesk@yahoo.com";
$headers = "From: $email";
$subject= "I'd like to discuss $projectType";
$message = "Name: $name\nEmail: $email\nProject Type: $projectType\nBudget: $budget\nDetails: $details";

mail($to, $subject, $message, $headers);
$response['message'] = "Thank you, $name, I will be in touch with you soon!";
}

echo json_encode($resposne) // this is needed inorder for the ajax to retrieve the data from the server

?>

您需要记住的内容如下:

  • 表单控件(即输入、文本区域等)仅需要最少量的信息、类型和 ID。
  • 大多数表单控制选项(例如disabled、require、readonly)都可以仅使用这些关键字来添加,因此您不需要执行诸如disabled='disabled'之类的操作
  • 在jquery中使用$.ajax时,在这种情况下您只需要url, type, data, dataType, success
  • 在 PHP 中干净地组织数据,以便以后代码更容易阅读
  • 使用 ajax 时,您必须将所有内容存储在单个响应数组中,并在完成后将该编码数组回显回服务器,否则您将无法检索该数据。

关于javascript - AJAX、JSON、PHP 联系表单、event.preventDefault 不起作用且数据未发送到电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30735961/

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