未选中的复选框验证将返回[object Object]

时间:2018-05-03 19:41:38

标签: javascript php jquery html html5

我正在使用jquery将已检查和未选中的复选框发送到PHP验证表单。 使用的jquery是:

 'updates'  : $('input:checkbox[name=updates]').is(':checked') ? 1 : 0

我想我必须验证错误,因为这会返回[object Object]解决他的最佳方法是什么?

用于发送formData

的javascript验证表单
function validateForm() {
document.getElementById('status').innerHTML = "Sending...";
formData = {
'name'     : $('input[name=name]').val(),
'surname'  : $('input[name=surname]').val(),
'email'    : $('input[name=email]').val(),
'subject'  : $('input[name=subject]').val(),
'message'  : $('textarea[name=message]').val(),
'updates'  : $('input:checkbox[name=updates]').is(':checked') ? 1 : 0
};


$.ajax({
url : "mail.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{

$('#status').text(data.message);
if (data.code) //If mail was sent successfully, reset the form.
$('#contact-form').closest('form').find("input[type=text], 
textarea").val("");
},
error: function (jqXHR, textStatus, errorThrown)
{   
$('#status').text(jqXHR);
}
});

}

服务器端的PHP验证

<?php
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$updates= $_POST['updates'];
header('Content-Type: application/json');

if ($updates){
 print json_encode(array('message' => 'Checkbox cannot be empty', 
                        'code' => 0));
} else{

exit();
}

$content="From: $name \nSurname: $surname \nEmail: $email \nMessage: 
$message";
$recipient = "*******@gmail.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
print json_encode(array('message' => 'Email successfully sent!',
'code' 
=> 
1));
exit();
?>

1 个答案:

答案 0 :(得分:0)

你得错了,因为在$updates == 1你打印了2个不同的JSON。用它改变PHP脚本。

<?php
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$updates= $_POST['updates'];
header('Content-Type: application/json');

if ($updated == 0){
 print json_encode(array('message' => 'Checkbox cannot be empty', 
                        'code' => 0));
} else{
$content="From: $name \nSurname: $surname \nEmail: $email \nMessage: 
$message";
$recipient = "*******@gmail.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
print json_encode(array('message' => 'Email successfully sent!',
'code' 
=> 
1));
}
?>