I'm setting up a Contact Form Validation and i need the variable $msg from a php script 'sendEmail.php'. The actual mailing system is working, the script is receiving the form input's from index.php and is working(Successfully sending emails)... The thing is the 'success: function(data)' isn't working, and have been couple days trying to figure out what i'm doing wrong
I've tried to change to $.post function, compared a lot of examples similar, debugging with the 'error:' function...
The error displays on the console 'console.log(errorThrown)'
I'm using Safari and i get this from the XHRs folder from the sendEmail.php: Output:
array(3) {
["name"]=>
string(12) "asfasfasfasf"
["email"]=>
string(9) "asfasfasf"
["message"]=>
string(0) ""
}
{"code":404,"msg":"Please fill in all fields"}
// AJAX Call
$.ajax({
type: "POST",
url: "php/sendEmail.php",
dataType: "json",
data: {
name: name,
email: email,
message: message
},
success: function(data) {
if (data.code == '200') {
$('.alert-success').html(data.msg);
$('.alert-success').css('display', 'block');
} else {
$('.alert-danger').html(data.msg);
$('.alert-danger').css('display', 'block');
}
},error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
// Error Message
$msg = '';
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])) {
// Get Form Data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
var_dump($_POST);
// Verifications
if (!empty($name) && !empty($email) && !empty($message)) {
// Name Check
if (strlen($name) <= 4 || strlen($name) >= 30) {
$msg = 'Please type a name between 4 and 30 characters';
} else {
// Email Check
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$msg = 'Please provide a valid email';
} else {
// Message Check
if (strlen($message) < 10) {
$msg = 'Please provide a message superior to 10 characters';
} else {
// Send Email
$msg = 'Email was sent successfully...';
echo json_encode(['code' => 200, 'msg' => $msg]);
exit;
} catch (Exception $e) {
$msg = 'Error: Email was not sent...';
}
}
}
}
} else {
$msg = 'Please fill in all fields';
}
}
echo json_encode(['code' => 404, 'msg' => $msg]);
``
echo json_encode(['code' => 404, 'msg' => $msg]);exit;after you echo the json-data to prevent anything else being executed. Also, check the network tab in the browsers dev-tools when you make a request so you can see what it actually returns. It could be some error message further up in the file.