I have a working html form with jQuery validation and have been submitting the data with AJAX, I am now trying to copy this form in to my own Wordpress theme, but I can't see where I am going wrong in using AJAX in Wordpress.
I am referencing subscribe.js in my headerand this is my form:
<div id="subscribe">
<input type="text" id="emailsub" class="text-input" name="email" placeholder="your email address" />
<input type="submit" src="<?php bloginfo('template_directory'); ?>/images/send.jpg" alt="Send" width="37" height="27" name="#" id="submitsub" class="contactbutton" />
<br />
<!-- Email Validation -->
<span id="errorSubEmail" class="subError"></span>
<span id="formSubProgress" class="subProgress"></span>
</div>
I am using some jQuery validation, but here is the AJAX:
$.ajax({
type: "POST",
url: "http://mywebsite.co.uk/wp/wp-admin/admin-ajax.php",
data: {
action: 'ajaxfunction',
email: email,
} ,
success: function(msg) {
//alert(msg);
// Check to see if the mail was successfully sent
if(msg=='Mail sent') {
// Update the progress bar
$('.email_wrap #formSubProgress').html('<img src="images/ajax-complete.png" /> Thankyou!').delay(2000).fadeOut(400);
// Clear the subject field and message textbox
// $('.email_wrap #subject').val('');
// $('.email_wrap #message').val('');
} else {
$('.email_wrap #formSubProgress').html('');
alert('There was an error sending your email. Please try again.');
}
// Activate the submit button
$('.email_wrap #submitsub').attr("disabled", "");
},
error: function(ob,errStr) {
$('.email_wrap #formSubProgress').html('');
alert('There was an error sending your email. Please try again.');
// Activate the submit button
$('.email_wrap #submitsub').attr("disabled", "");
}
});
And my functions.php:
add_action('init', 'add_contact_script');
function add_contact_script() {
wp_register_script('contact', get_bloginfo('template_directory') . '/subscribe.js', array('jquery'), '1.0' );
wp_enqueue_script('contact');
}
function ajax_contact() {
if(!isset($_POST['email'])
) {
die('Error: aaaa Missing variables');
}
}
function ajaxfunction() {
// die("ajaxfunction is called");
if(!isset($_POST['email']) ) {
die('Error: Missing variables');
} else {
$email=$_POST['email'];
$to='you@email.com';
$headers = 'The following person has registered to be notified when your webite launches: '."\r\n" ."\r\n" .
'Email: '.$email."\r\n";
$subject = 'A new person has registered to be updated when you go live';
if(mail($to, $subject,
$headers)) {
die('Mail sent');
} else {
die('Error: Mail failed');
}
}
}
add_action( 'wp_ajax_nopriv_ajaxfunction', 'ajaxfunction' );
add_action( 'wp_ajax_ ajaxfunction', 'ajaxfunction' );
jQuery()instead of the unsupported$? – toscho♦ Jul 2 '12 at 18:38