I have a page-contact.php for my contact form in my template. I wanted to add jquery validation and some fancy ajax action to my form. This is already a working code in a simple PHP page, but getting it work in wordpress fails.
My contact form:
<form id="contact_form" method="POST" action="" enctype="application/x-www-form-urlencoded" novalidate="novalidate">
<input type="text" name="name" maxlength="30" id="name" placeholder="Your name">
<input type="text" name="email" maxlength="30" id="email" placeholder="Your email">
<textarea rows="2" cols="40" name="message" id="message" placeholder="Your message"></textarea>
<input type="text" id="phone" name="phone" size="15" placeholder="Please do not fill your phone number">
<input type="submit" id="click" class="button" value="Submit">
<div id="loading_icon"><img src="/wp-content/themes/owlish/img/loading.gif" alt="loading"></div>
<div id="response"></div>
</form>
the ajax function in functions.php
add_action('wp_ajax_sendmail', 'sendmail');
add_action('wp_ajax_nopriv_sendmail', 'sendmail');
function sendmail() {
if(isset($_POST['Submit'])) {
echo 'ajax success';
} else {
echo "<p class='error'>nothing submitted</p>";
}
die();
}
And my javascript action:
$(document).ready(function(){
$("#contact_form").validate({
rules: {
name: "required",
email: {
required: true,
email: true
},
message: "required"
},
messages: {
name: "Please enter your name",
email: {
required: "Please enter your email adress",
email: "Please enter your valid email adress"
},
message: "Please enter a short message, what your inquiry is about"
},
submitHandler: function(form) {
$('#loading_icon').show();
$('#click').hide();
var params = $(form).serialize();
$.ajax ({
type: 'POST',
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: params,
success: function(response) {
$('#response').hide();
$('#response').html(response);
$('#response').fadeIn('slow');
$('#loading_icon').hide();
}
});
}
});
});
The needed files are loaded correctly (/1.10.1/jquery.min.js, jquery.validate.js) but, this code keeps returning 0 despite the fact that I have wp_ajax_nopriv_sendmail
in functions.php. The console does not return any error. I believe that I am missing some wp-specific fact, but which?
Thanks in advance
0
is returned in case a action callback isn't found.action
param for your AJAX hook to fire:data: params + "&action=sendmail",