I have a form on a Wordpress site that I first validate with the jQuery Validate plugin, and then submit via AJAX. On submit, an email is sent that uses the information included in the form.
The form has four fields: Name, Email, Website, Message. The first three are required, while the Message field is optional. If I fill in all the fields, everything works fine and the email gets sent. However, if I leave the Message field blank, the email doesn't get sent, even if Message is optional.
By the way, I'm working locally so I'm using Mailtrap as a SMTP server.
Here's the form's HTML:
<form id="submit-work-cf" class="contact-form" method="post" action="submit_work" novalidate>
<input type="text" id="name" name="name" placeholder="Your full name">
<input type="email" id="email" name="email" placeholder="Your email address">
<input type="text" id="url" name="url" placeholder="Your website">
<textarea id="message" name="message" rows=7 placeholder="Additional info" value=""></textarea>
<input type="submit" value="Submit your work" />
</form>
Here's my script:
var form = $( '.contact-form' );
form.validate({
rules: {
name: 'required',
url: 'required',
email: {
required: true,
email: true
}
},
messages: {
name: 'Your name is required',
url: 'A link is required',
email: {
required: 'An email address is required',
email: 'Please enter a valid email address'
}
},
submitHandler: function() {
var action = form.attr( 'action' );
var params = form.serialize();
$.ajax({
url: ajax.url,
type: 'post',
data: params + "&action=" + action,
error: function ( response ) {
showNotification( 'Oops, there was an error. Please try again later', 5000 );
},
success: function ( response ) {
showNotification( 'Submission received. Thank you for contacting us!', 5000 );
}
});
}
});
And here's my AJAX callback:
add_action( 'wp_ajax_submit_work', 'submit_work' );
add_action( 'wp_ajax_nopriv_submit_work', 'submit_work' );
function submit_work() {
$name = isset( $_POST[ 'name' ] ) ? wp_strip_all_tags( $_POST[ 'name' ] ) : '';
$email = isset( $_POST[ 'email' ] ) ? wp_strip_all_tags( $_POST[ 'email' ] ) : '';
$url = isset( $_POST[ 'url' ] ) ? wp_strip_all_tags( $_POST[ 'url' ] ) : '';
$message = isset( $_POST[ 'message' ] ) ? wp_strip_all_tags( $_POST[ 'message' ] ) : '';
$site = get_bloginfo( 'name' );
$to = 'mymail@mysite.com';
$subject = 'Email by ' . $name;
$headers[] = "From: $site <$to>";
$headers[] = "Reply-To: $name <$email>";
$headers[] = 'Contenet-Type: text/html: charset=UTF-8';
wp_mail( $to, $subject, $message, $headers );
die();
}
+++ UPDATE AND SOLUTION +++
My question was marked as a duplicate of another one, so I can't post an answer; but I've resolved my issue simply checking the $_POST
variables with !empty
instead of isset
.