Using WordPress ajax

WordPress Core Api provides some functions for handling ajax calls. Unlike usual jQuery ajax, WordPress ajax is quite different.This post is intended to give you a brief overview on using WordPress ajax in your themes and plugins.

For the sake of this tutorial lets create a simple form that shall take in the username and check if there exists a user with the username provided.

Html markup

Insert your username below

Create a test page and copy the above code.

jQuery Code

jQuery(document).ready(function($) {

	$("#ajax-login-submit").click(function(){

		var data = {
			action: 'login_in_using_ajax';
			username: $("#ajax-login-username");
		};

	        var ajaxurl = '';    

		$.post(ajaxurl, data, function(response) {
			if(response==true)
	                $("#ajax-login-form").html("User exists.");
	                elseif(response==false)
	                $("#ajax-login-message").html("User does not exist.");
		});

		return false;

	});

});

In the above code, note the use of action parameter in the data array. The value of this parameter i.e. login_in_using_ajax will be used by WordPress to locate the callback function that will handle this ajax request.

PHP Code
In your active theme’s function.php file copy the following code.

 

add_action('wp_ajax_login_in_using_ajax', 'login_in_using_ajax_callback');

function login_in_using_ajax_callback() {
	if ( username_exists( $_POST["ajax-login-username"] ) )
        return true;
        else
        return false;
	die();
}

Things to note here

  • wp_ajax_login_in_using_ajax
    login_in_using_ajax_callback

    Here login_in_using_ajax is our the action parameter passed to the data array in our jQuery code. This is how WordPress handles ajax call, by using wp_ajax_[value_of_action_parameter] and [value_of_action_parameter]_ajax_callback.
    As the name indicates the latter is a callback php function i.e. [value_of_action_parameter]_ajax_callback will handle our ajax call.
    The data passed using ajax will be available as POST parameter here.
    After validating the data we can echo an appropriate result. Whatever is echo’ed () will be available in the response parameter in the jQuery code.
  • die() This is needed for returning a proper result.

Reference

http://codex.wordpress.org/AJAX_in_Plugins

Leave a Reply

Your email address will not be published. Required fields are marked *