Solution:
Validate both ways. JS validation makes for a smooth UX and takes care of most concerns regarding valid email addresses, non-empty fields etc.
PHP validation will ensure that your functions don’t error out and can allow you to do some server side checks (like exact message hasn’t been sent before etc)
In php, do your validation checks and prepare a json response of any errors, then echo that back (rather than proceed with the code) if there are errors. In JS catch the errors in your success block – which right now doesn’t listen for any response.
PHP:
if ($errors) {
echo json_encode(array('status' => 'error', 'message' => 'Your email message has objectionable content'));
wp_die();
}
if (!wp_mail($to, $subject, $msg)) {
echo json_encode(array('status' => 'error', 'message' => 'Your email message did not send for some reason'));
wp_die();
}
echo json_encode(array('status' => 'success');
wp_die();
Your JS
// ajax...
$.ajax({
... your props
dataType: 'json',
success: function (response) {
if (response && response.status == 'error'){
$('errors').html("Sorry, your message did not get sent due to these errors: " + response.message);
return;
} else {
// .. success