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

Create a test page and copy the above code.

jQuery Code

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.

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 *