gpt4 book ai didi

javascript - PHP/Ajax 联系表单重定向到 PHP 文件

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

我正在为我正在处理的投资组合开发联系表单,当我单击提交按钮发送消息时,页面不会在表单下方显示引导警报消息,而是重定向到PHP 文件。

提交有效详细信息后,我的收件箱中收到了来自表单的电子邮件,但即使我使用 ajax,我仍然会被重定向。

示例位于 http://nickcookweb.co.uk/#contact .

编辑:preventDefault();似乎根本不起作用。

HTML:

<form id="contactForm" name="contactForm" action="contact.php" method="POST">

<input type="text" name="name" id="name" placeholder="Full Name (Required)" required/>

<input type="email" name="email" id="email" placeholder="Email (Required)" required/>

<input type="tel" name="tel" id="tel" placeholder="Contact Number"/>

<textarea type="text" name="message" id="message" placeholder="Message (Required)" required></textarea>

<button type="submit" id="sendButton" class="button">Send<span class="fa fa-paper-plane" aria-hidden="true" style="margin-left:6px; top:2px"></span></button>

</form>

<div id="contactSuccess" class="alert alert-success">
<span>
<p>Message sent successfully.</p>
</span>
</div>

<div id="contactError" class="alert alert-danger">
<span>
<p>There was an error sending your message. Please try again.</p>
</span>
</div>

PHP:

<?php

$to = "contact@nickcookweb.co.uk";

$from = $_REQUEST['email'];

$name = $_REQUEST['name'];

$message = $_REQUEST['message'];

$headers = "From: $from";

$subject = "New Message via Portfolio";

$fields = array();

$fields{"name"} = "name";

$fields{"email"} = "email";

$fields{"tel"} = "tel";

$fields{"message"} = "message";

$body = "Details:";

foreach($fields as $a => $b) {

$body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]);

}

$send = mail($to, $subject, $body, $headers);

?>

JS:

$(function() {
$('#contactForm').validate({
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
tel: {
required: true
},
message: {
required: true,
minlength: 10
}
},
messages: {
name: {
required: "Please provide your name",
minlength: "Your name must be at least 2 characters long"
},
email: {
required: "Please provide your email address"
},
message: {
required: "Please enter a message",
minlength: "Your message must be at least 10 character long"
},
},
submitHandler: function(form) {
$(form).ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"contact.php",
success: function() {
$('#contactForm :input').attr('disabled', 'disabled');
$('#contactForm').fadeTo( "slow", 0.15, function() {
$(this).find(':input').attr('disabled', 'disabled');
$(this).find('label').css('cursor','default');
$('#contactSuccess').fadeIn();
});
},
error: function() {
$('#contactForm').fadeTo( "slow", 0.15, function() {
$('#contactError').fadeIn();
});
}
});
}
});
});

最佳答案

$('#yourButton').on('click', function{ 
event.preventDefault();
//do your ajax and on success show msg
})

关于javascript - PHP/Ajax 联系表单重定向到 PHP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38573804/

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