Can someone help me please? I have a problem with sending AJAX request and validate it on backend php script.
So this is my code: PHP Handler (smtp settings 100% valid and tested):
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once('PHPMailer/Exception.php');
require_once('PHPMailer/PHPMailer.php');
require_once('PHPMailer/SMTP.php');
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
exit();
}
if ($_SERVER['REQUESTED_METHOD'] != 'POST') {
exit();
}
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['name']) && isset($_POST['message'])) {
function secure_input($data)
{
$data = trim($data);
$data = filter_var($data, FILTER_SANITIZE_STRING);
$data = str_replace(array("\r", "\n"), array(" ", " "), $data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = secure_input($_POST["name"]);
$message = secure_input($_POST["message"]);
if(!empty($_FILES['attachment']))
{
$file_name = $_FILES['attachment']['name'];
$file_tmp_name = $_FILES['attachment']['tmp_name'];
$file_size = $_FILES['attachment']['size'];
if($file_size < '2048000')
{
$file_path = move_uploaded_file($file_tmp_name, $file_name);
}else{
print json_encode(['error'=>1,'msg'=>"Oops! File upload size exceeded...", $file_size]);
exit;
}
}
$mail = new PHPMailer(true);
$mail->CharSet = 'UTF-8';
$mail->IsSMTP();
$mail->SMTPDebug = 4;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "ssl";
$mail->Port = 465;
$mail->Username = "smtp.user";
$mail->Password = "smt.pass";
$mail->Host = "smtp.domain.com";
$mail->Mailer = "smtp";
$mail->SetFrom("email@domain.com");
$mail->AddReplyTo($_POST["email"]);
$mail->AddAddress("my@gmail.com");
$mail->IsHTML(true);
$mail->Subject = ("MyForm Subject");
$mail->Body = "
<h1>Hello dear admin!</h1>
<p>I am your personal mail delivery robot.</p>
<b>I have something new for you submitted from the form myForm</b>
Message: <p>$message</p>
";
$mail->WordWrap = 80;
$mail->MsgHTML($_POST["message"]);
if (is_array($_FILES['attachment'])) {
$mail->AddAttachment($file_tmp_name, $file_name);
}
if (!$mail->send()) {
$message = 'Error';
}else{
$message = 'Email sent successfully';
}
}
$response = ['message' => $message];
header('Content-type: application/json');
echo json_encode($response);
jQuery code;
$(document).ready(function() {
$("#submitMyForm").click(function(e) {
e.preventDefault();
jQuery.validator.addMethod("validDate", function(value, element) {
return this.optional(element) || moment(value, "MM/DD/YY").isValid();
}, "Please enter a valid date in the format MM/DD/YY");
jQuery.validator.addMethod("phoneTest", function(value, element) {
if (/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/.test(value)) {
return true;
} else {
return false;
};
}, "Invalid phone number");
$("#myForm").validate({
rules: {
scheduleAudience: {
required: true,
},
date: {
required: true,
validDate: true
},
time: {
required: true
},
fName: {
required: true,
lettersonly: true,
minlength: 2,
maxlength: 30
},
lName: {
required: true,
lettersonly: true,
minlength: 2,
maxlength: 30
},
email: {
required: true,
email: true
},
phone: {
required: true,
phoneTest: true
},
preferences: {
required: true
},
message: {
required: true,
minlength: 20,
maxlength: 500
},
messages: {
fName: {
minlength: "Please, provide information with minimum - 2 Characters",
maxlength: "Please, provide information with maximum - 30 Characters"
},
lName: {
minlength: "Please, provide information with minimum - 2 Characters",
maxlength: "Please, provide information with maximum - 30 Characters"
},
message: {
minlength: "Please, provide information with minimum - 20 Characters",
maxlength: "Please, provide information with maximum - 500 Characters"
}
},
}
});
if ((!$('#myForm').valid())) {
return false;
}
if (($('#myForm').valid())) {
var formData = $("#myForm").serialize();
var URL = $("#myForm").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(data) {
alert(JSON.stringify(response));
if (response.status == 1) {
swal({
title: "Good job!",
text: "We will get in touch with you soon",
icon: "success",
});
}
},
error: function(response) {
alert(JSON.stringify(response));
}
});
}
})
$("#attachment").change(function() {
var file = this.files[0];
var fileType = file.type;
var match = ['image/jpeg', 'image/jpg', 'image/png'];
if (!((fileType == match[0]) || (fileType == match[1]) || (fileType == match[2]))) {
swal({
title: "Invalid file format",
text: "Sorry, only JPEG, JPG and PNG files are allowed to upload!",
icon: "error",
});
$("#attachment").val('');
return false;
}
});
});
HTML form
<form class="contact100-form validate-form" id="myForm" name="myForm" action="URL_TO_PHPSCRIPT" method="post">
Now i get an error: Uncaught ReferenceError: response is not defined
without dataType: "json", and i think it's because i use response in alert in success method, i need replace it to data? With dataType: "json" i get an error: {"readyState":4,"responseText":"","status":200,"statusText":"parsererror"}
What is the correct way to validate the form in this case? And force to work phpmailer
I have reduced the code length a bit by removing the declarations of other variables for convenience.
In general, I tried a lot of things and came to the conclusion that there was an error in the PHP handler. I already broke my whole head, until I really understand what the problem is.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.