Aug
02
2010

Using Ajax with WordPress

by   |  Posted in Tutorials  |  4 comments

A little while back, I updated Magazine Basic and added the Ajax save function. When I uploaded it to WordPress to await approval, I received some feedback on how I could incorporate Ajax using the admin-ajax.php file instead of the sloppy way I had it coded. All of the core Ajax functions in WordPress rely on admin-ajax.php and using it for custom scripts is extremely easy to implement.

Let’s take a look at all the pieces you need to get it working. In this example I will build a small mailing list function that will send out an email to the admin when a person clicks submit.

Here’s our form:

<form method="post" id="mailinglist" action="">
	<div id="message"></div>
	<input type="text" name="mailinglistemail" id="mailinglistemail" />
	<input type="submit" name="submit" id="mailinglistsubmit" value="Join" /><img src="<?php admin_url(); ?>/wp-admin/images/wpspin_light.gif" alt="" class="ajaxsave" style="display: none;" />
</form>

Here’s the jQuery:

jQuery(document).ready(function(){
	jQuery("#mailinglist").submit(function()	{
		if(jQuery("#mailinglistemail").val()=="") {
			jQuery("#mailinglist #message").text("Please enter your email address.");
			return false;
		} else {
			var email = jQuery('#mailinglistemail').val();
			if(email.indexOf("@") == -1 || email.indexOf(".") == -1) {
				jQuery("#mailinglist #message").text("Please enter a valid email address.");
				return false;
			} else {
				var data = {
					action: 'join_mailinglist',
					email: email
				};
				jQuery("#mailinglistsubmit").hide();
				jQuery(".ajaxsave").show();
				jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data,
				function(response){
					jQuery(".ajaxsave").hide();
					jQuery("#mailinglistsubmit").show();
					jQuery("#mailinglist #message").html(response);
				});		
				return false;
			}
		} 
 
	});
});

Let me explain each part.

When a user clicks submit, we need to check that the email field is not empty. If it is empty, we let the user know by sending the “Please enter your email address.” message and we stop the form from being submitted by including the return false; line.

if(jQuery("#mailinglistemail").val()=="") {
	jQuery("#mailinglist #message").text("Please enter your email address.");
	return false;
}

Next, we’ll do a simple validation to make sure the email address actually contains the @ symbol and a period. If not, send an error message and return false.

var email = jQuery('#mailinglistemail').val();
if(email.indexOf("@") == -1 || email.indexOf(".") == -1) {
	jQuery("#mailinglist #message").text("Please enter a valid email address.");
	return false;
}

Once all that is done and everything is good, we can submit our form. This is where admin-ajax.php comes into play. When using admin-ajax.php, you need to include an action callback to make it work. Our callback is join_mailinglist. This is going to interact with our PHP to make everything work on the backend. Let’s create a data variable to store our action and our email value.

var data = {
	action: 'join_mailinglist',
	email: email
};

Now we will hide our submit button and have a loader graphic appear to let people know something is going on. Then will will use the jQuery .post function to send everything out to the admin-ajax.php file. Once the function is complete and a response is given, the loader will disappear, the submit button will return and a success message, or error message will indicate what happened.

jQuery("#mailinglistsubmit").hide();
jQuery(".ajaxsave").show();
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data,
function(response){
	jQuery(".ajaxsave").hide();
	jQuery("#mailinglistsubmit").show();
	jQuery("#mailinglist #message").html(response);
});		
return false;

With the form and the jQuery in place, all we need now is some PHP.

The admin-ajax.php file requires two action filters.

add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');

The first action will only work if users are logged in. The second is if users don’t have to be logged in. For our requirements, it should look like this:

add_action('wp_ajax_join_mailinglist', 'join_mailinglist_callback');
add_action('wp_ajax_nopriv_join_mailinglist', 'join_mailinglist_callback');

Here is our join_mailinglist_callback function, which needs to be added to functions.php:

function join_mailinglist_callback() {
	$email = $_POST['email'];
	if(!empty($email)) {
		$yourEmail = '[email protected]';
		$subject = 'Add me to your mailing list';
		$success = mail($yourEmail, $subject, $email);
		if(!empty($success)) {
			echo 'Your email is subscribed to our mailing list.';
		} else {
			echo 'There was a problem. Please try again.';
		}
	}
	die();
}

With everything in place, you will get a form that works like the one below.


About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , , , , , , , , , , , ,

Short URL: http://bit.ly/aXFOSJ

Discussion 4 Comments

  1. VDigital on August 6, 2010 at 4:54 pm

    May I suggest to add for each modified file their name and their relative path.
    And if you can why you choose this file and not another one.

    For your jQuery file, for the 2 add_action, for the form …
    Thanks.

  2. VDigital on August 6, 2010 at 5:01 pm

    Just a global remark: to other readers, if you intent to use this excellent tip within a plugin please do not forget to i18n with gettext functions.

  3. alex on September 24, 2010 at 10:03 am

    Can you explain me more about using i18n with gettext functions in ajax hook ?

    I use

    __()

    in my wp_ajax_myfunction

    But when jQuery put this in a div, the string are never translated.
    I don’t know why, because on the front end with out ajax that’s wordking.

    Please, thx for answer.

  4. jam on March 20, 2011 at 11:13 am

    thansk so much ! i am finding such a ajax to send mail !