I just got this code from a tutorial. I can’t seem to get it to work.
HTML (home.php)
<form name="myform" id="myform" action="" method="POST">
<!-- The Name form field -->
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value=""/>
<br>
<!-- The Email form field -->
<label for="email" id="email_label">Email</label>
<input type="text" name="email" id="email" size="30" value=""/>
<br>
<!-- The Submit button -->
<input type="submit" name="submit" value="Submit">
</form>
<!-- We will output the results from process.php here -->
<div id="results"><div>
PHP (function.php)
function myform(){
echo "Form submitted successfully: <br>Your name is <b>".$_POST['name']."</b> and your email is <b>".$_POST['email']."</b><br>";
}
add_action('wp_ajax_myform', 'myform');
add_action('wp_ajax_nopriv_myform', 'myform');
Javascript (header.php)
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#myform").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please let us know who you are.",
email: "A valid email will help us get in touch with you.",
},
submitHandler: function(form) {
// do other stuff for a valid form
jQuery.post('/wp-admin/admin-ajax.php', jQuery("#myform").serialize(), function(data) {
jQuery('#results').html(data);
});
}
});
});
</script>
4 Answers
This was very frustrating to figure out. I spent hours on this issue and discovered your problem is in this input:
<input type="text" name="name" id="name" size="30" value=""/>
Try changing the input field name to anything but “name”, for example:
<input type="text" name="user_name" id="name" size="30" value=""/>