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
http://codex.wordpress.org/AJAX_in_Plugins