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 = 'c@bavotasan.com';
		$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.