I'm using the code below for my contact form. The issue is that as long as the users fill in all the fields in the contact form and bootstrap validator checks are passed, the "success" message is displayed when they click "send". It means that even when the PHP file is completely emptied or does not contain the correct smtp parameters (so for sure the message will never be sent), the success message is still displayed.
How can I adapt the JS code so that it also takes into consideration the results of the PHP script?
I'm not familiar with PHP and JS but I guess it should be something like this:
When user click "send", check bootstrapvalidator results.
If OK, obtain result from PHP script (success or failure)
If both bootstrapvalidator and PHP script are OK, display "success" message. If not, display "alert" message.
Thanks for your help
$(document).ready(function() {
$('#contact_form').bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
submitHandler: function(validator, form, submitButton) {
$('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...
$('#contact_form').data('bootstrapValidator').resetForm();
$('button[name="submit"]').hide();
var bv = form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post(form.attr('action'), form.serialize(), function(result) {
console.log(result);
}, 'json');
},
fields: {
first_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'Please supply your first name'
}
}
},
message: {
validators: {
stringLength: {
min: 10,
max: 200,
message:'Please enter at least 10 characters and no more than 200'
},
notEmpty: {
message: 'Please supply a description of your project'
}
}
}
}
})
});
PHP:
$mail->Subject = "New message from " . $_POST['first_name'] . $_POST['last_name'];
$mail->Body = $_POST['message']."<br><br>From page: ". str_replace("http://", "", $_SERVER['HTTP_REFERER']) . "<br>" . $_SERVER ['HTTP_USER_AGENT'] ;
$response = array();
if(!$mail->send()) {
$response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
} else {
$response = array('message'=>"Message has been sent successfully", 'status'=> 1);
}
/* send content type header */
header('Content-Type: application/json');
/* send response as json */
echo json_encode($response);
?>