Javascript 成功处理表单后,如何执行操作?
我想将表单隐藏,并在表单成功提交后显示一条感谢消息。我已经完成了以下代码,但我无法在提交表单后执行任何操作。。就像忽略了“if”函数一样 下面是我的代码: JQuery:Javascript 成功处理表单后,如何执行操作?,javascript,php,jquery,ajax,forms,Javascript,Php,Jquery,Ajax,Forms,我想将表单隐藏,并在表单成功提交后显示一条感谢消息。我已经完成了以下代码,但我无法在提交表单后执行任何操作。。就像忽略了“if”函数一样 下面是我的代码: JQuery: $('form#contactform').submit(function(event) { var formData = { //get form data 'name' : $('input[name=name]').val(), 'email' : $('input[name=email]')
$('form#contactform').submit(function(event) {
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val(),
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
//Done promise callback
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (! data.success == true) {
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
} else {
alert("An internal error has occured");
}
});
//Stop form default action
event.preventDefault();
Php:
任何帮助都将不胜感激。谢谢。您需要告诉浏览器您希望看到什么。因此,在echo之前添加header函数
header('Content-Type: application/json'); // this line here
echo json_encode($data);
更新
还有你的event.preventDefault;最后一个,这应该是在$'formcontactform'.submitfunctionevent{之后调用的第一件事,因为您希望在ajax调用之前阻止这些内容
另外,PHP在邮件函数返回值的任何一种情况下都会回显内容,因此json响应会出错,因此ajax将无法返回正确的数据
更新2
我有一种强烈的感觉,你的PHP脚本正在抛出某种类型的错误。例如,邮件函数可能会抛出530错误。因此,最好禁用PHP脚本中的错误显示。
调试这类东西的一般建议是查看请求/响应信息
请尝试此重构代码:
ini_set('display_errors',0); // disable error displaying. Rather view in logs
$errors = array(); //array to hold validation errors
$data = array(); //array to pass back data
//validate variables
if (empty($_POST['name']))
$errors['name'] = 'Name is required';
if (empty($_POST['email']))
$errors['email'] = 'E-Mail is required';
if (empty($_POST['subject']))
$errors['subject'] = 'Subject is required';
if (empty($_POST['message']))
$errors['message'] = 'Please enter a message';
//Return response
if ( ! empty($errors)) { //If there are errors
$data['errors'] = $errors; // only necessary to set errors
} else {
//Process form
$name = $_POST['name'];
$email = $_POST['email'];
$re = $_POST['subject'];
$message = $_POST['message'];
$from = 'info@jamescremona.com';
$to = 'jmscre@gmail.com';
$subject = 'Form submission';
$body = "From: $name\n E-mail: $email\n Subject: $re\n Message: $message\n";
if (mail ($to, $subject, $body, $from)) {
$data['success'] = 'Your message has been sent!'; // store to $data instead of echo out
} else {
$data['errors'] = 'Something went wrong, go back and try again!'; // store to $data instead of echo out
}
}
header('Content-Type: application/json');
echo json_encode($data);
以及ajax调用的done函数中的javascript片段:
<script type="text/javascript">
$('#contactform').submit(function(event) {
event.preventDefault(); // note this one has to be at the beginning of your submit function since you do not want to submit
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val(),
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
//Done promise callback
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (data.success) { // success either exists or not
alert("Success! Form should hide now...");
$('#contactform').hide(); // an id is (should always) be unique. So you dont need this "section#contact form#contactform". It does not make sense. Also hide and show are functions and need brackets at the end
$('div.thxform').show();
} else { // then its an error
alert("An internal error has occured");
}
});
});
</script>
我用来测试的HTML:
<form method="post" id="contactform">
Name <input type="text" name="name" value="test"><br>
Email <input type="text" name="email" value="test@localhost.com" ><br>
Subject <input type="text" name="subject" value="subject" ><br>
Message <textarea name="message" ></textarea><br>
<input type="submit">
</form>
这是因为两个小错误: [js代码]将if!data.success==true替换为if data.success==true。 [php代码]在回显$data之前添加标题'Content-Type:application/json'
我想问题就在这里
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
和Javascript
.done(function(data) {
if (typeof data !== 'object') {
alert('Expected data as object - '+typeof data+' received');
return;
}
data = jQuery.parseJSON(data);
//Errors and validation messages
if (data.success == true) {
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
} else {
alert(data.message);
}
});
请注意,@before-mail函数不会生成错误消息以避免在Javascript上发送字符串。我在代码中发现的第一个错误: 'message':$msg.val,这是数组中的最后一项,因此不需要使用“'javascript expect more items after',” 您需要检查控制台中的所有js错误,它们就在那里 然后我看到的第二个错误 $'sectioncontact formcontactform'。隐藏; $'sectioncontact div.thxform'。显示; show和hide在jquery中不存在,它们有show;和hide;然后在这里:if!data.success==true{} 以下是代码的外观:
<script type="text/javascript">
$('form#contactform').submit(function(event) {
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val()
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (!data.success) {
$('section#contact form#contactform').hide();
$('section#contact div.thxform').show();
//check which field was wrong and show the user
if(data.errors.name){
$('section#contact div.thxform').append(data.errors.name);
}
if(data.errors.email){
$('section#contact div.thxform').append(data.errors.email);
}
if(data.errors.subject){
$('section#contact div.thxform').append(data.errors.subject);
}
if(data.errors.message){
$('section#contact div.thxform').append(data.errors.message);
}
}else{
$('#successDIV').append(data.message);
}
}),
.fail(function(data){
//debugging puporses, all your php errors will be printed in the console
console.log(data);
});
//Stop form default action
event.preventDefault();
</script>
对于该ajax请求,您还应该有一个失败的回调。console.logdata;的内容是什么?只是一件简单的小事情,检查您的控制台问题就在这里:$'sectioncontact formcontactform'.hide;$'sectioncontact div.thxform'.show;does函数在JQuery上不存在这就是您应该拥有的$'sectioncontact formcontactform'.hide;$‘sectioncontact div.thxform’.show;添加了行,但仍然没有成功感谢您的支持!不幸的是,我仍然没有成功。为了排除故障,我在ajax调用的done函数中发出了一个警报。我相信在提交表单和发送电子邮件后,这应该会给我一个警报,不是吗?在我的情况下,我不是获取任何信息。可能我的php代码没有通知ajax.done该过程实际上已经完成了?我再次编辑了javascript,因为我错误地使用了您的旧代码段……我认为这是某种诅咒……我已经完成了一个测试页面,并使用了您建议的代码……但是,表单正在提交中,我收到了电子邮件,但仍然没有收到表单没有更改,我也没有收到任何警报。控制台没有显示任何错误,服务器也没有生成任何错误日志。这让我发疯……你会到达的。我再次更新了我的答案。请注意完成函数中的修复jQuery。你的选择器仍然混乱。这可能就是为什么即使这样也不会发生任何事情的原因一切正常。如果这仍然没有帮助,请转储您的HTML表单。它仍然没有进入“如果”状态。我既没有看到元素上的隐藏/显示,也没有看到警告消息:您可以检查浏览器控制台以查看是否有错误吗?控制台完全没有显示错误,并且正确发送包含表单数据的电子邮件我开始认为问题要么在于php发送数据数组的方式,要么在于如何调整数据大小,要么在于如何在Java脚本中将数据分配给变量。
.done(function(data) {
if (typeof data !== 'object') {
alert('Expected data as object - '+typeof data+' received');
return;
}
data = jQuery.parseJSON(data);
//Errors and validation messages
if (data.success == true) {
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
} else {
alert(data.message);
}
});
<script type="text/javascript">
$('form#contactform').submit(function(event) {
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val()
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (!data.success) {
$('section#contact form#contactform').hide();
$('section#contact div.thxform').show();
//check which field was wrong and show the user
if(data.errors.name){
$('section#contact div.thxform').append(data.errors.name);
}
if(data.errors.email){
$('section#contact div.thxform').append(data.errors.email);
}
if(data.errors.subject){
$('section#contact div.thxform').append(data.errors.subject);
}
if(data.errors.message){
$('section#contact div.thxform').append(data.errors.message);
}
}else{
$('#successDIV').append(data.message);
}
}),
.fail(function(data){
//debugging puporses, all your php errors will be printed in the console
console.log(data);
});
//Stop form default action
event.preventDefault();
</script>