我正在创建一个向我发送电子邮件的表单,但不会加载新页面,而只是在同一页面上修改一些HTML和CSS值。
我试图实现它,它接近完成,它只是无法正常工作。单击提交后,它不验证表单,它加载PHP页面并说“谢谢...”,然后我收到一封电子邮件。如果你能帮助我理解和调试它,我真的很感激。谢谢!
我可以确认jQuery是否正确链接。我按此顺序进行设置:
<html>
<head>
<script> (link for jquery)
<style>
<script>
validateForm() JavaScript
jQuery
<body> (no loading functions via onload)
HTML表单:
<form id='form' method='post' action='sendemail.php'>
Name: <br />
<input type="text" id="name" name="name" />
<br /><br />
Email: <br />
<input type="email" id="email" name="email" />
<br /><br />
Subject: <br />
<input type="text" id="subject" name="subject" />
<br /><br />
Comments: <br />
<textarea id="comments" name="comments" rows="10" cols="60"></textarea>
<br /><br />
<input type="image" src="..." name="myFormSubmitted" value="Submit" />
</form>
<div id="formResponse"></div>
PHP - sendmail.php:
<?php
if(isset($_POST['myFormSubmitted'])) {
$message = '';
// Construct the message
$message .= <<<TEXT
Name: {$_POST['name']}
Email: {$_POST['email']}
Subject: {$_POST['subject']}
Comments: {$_POST['comments']}
{$checkString}
TEXT;
$to = 'sendMeHere@example.com';
$subject = $_POST['subject'];
$from = $_POST['name'];
$fromEmail = $_POST['email'];
$header = 'From: ' . $from . '<' . $fromEmail . '>';
// Send the email
mail($to, $subject, $message, $header);
echo 'Thank you for your Email. We will get in touch with you very soon.';
}
?>
jQuery的:
//On form submit, call validateForm, then post to PHP if validated
$("#form").submit(function(e) {
if (validateForm()) {
$.post(
'sendemail.php',
{
name: $('#name').val(),
email: $('#email').val(),
comments: $('#comments').val(),
myFormSubmitted: 'yes'
},
function(data) {
$("#formResponse").html(data).fadeIn('100'); //Place echo in div
//Modify HTML & CSS here
$('#name, #email, #comments').val(''); //Clear the inputs - I don't understand this line
},
'text'
);
}
//Prevent event from bubbling
e.preventDefault();
e.stopPropagation();
return false;
});
JavaScript验证功能:
$(document).ready(function() {
function validateForm() {
var validName = false;
var validEmail = false;
var validSubject = false;
var validComments = false;
//Perform validation here...
if (validName && validEmail && validSubject && validComments) {
return true;
} else {
return false;
}
});
答案 0 :(得分:0)
你应该将你的javascript包装在一个就绪的事件处理程序中,如下所示:
$(document).ready(function() {
// Your javascript here...
});
答案 1 :(得分:0)
删除html表单标记上的“action ='sendemail.php'”属性。
答案 2 :(得分:0)
只是另一种解决方案。您可以在输入[type = image]的单击事件中提交表单提交触发器。我没有检查过,但希望有效!
$('input[type=image]').click(function(e){
e.preventDefault();
$('#form').submit();
});