Ajax is what you can call the present and future of interactive website interface. Lots of WordPress developers are not aware with the Ajax support in WordPress. They think it will be hard to use Ajax in there Plugins and Themes. But let me tell you that WordPress makes it really easy to implement Ajax in your WordPress theme or plugin. I am going to tell you how ;)

First we will see the Server side code:-

add_action(“wp_ajax_ActionForJS”,”FunctionToBeCalled”);

You need to declare the Action name for Ajax request wp_ajax_ + name.

The second argument is the callback function which will be executed at the time of Ajax request. For simplicity we can make both of them same like this:-

add_action(“wp_ajax_FunctionName“,”FunctionName”);

Now define the call back function as follow:-

function FunctionName()
{
$res= new WP_Ajax_Response;
if(!current_user_can(‘manage_options’) )
{
$res->add(array(‘data’=>’error’,’supplemental’=>array(‘message’=>”You don’t have permission!”)));
}
else
{
$res->add(array(‘data’=>’success’,’supplemental’=>array(‘message’=>”complete”)));
}
$res->send();
die();
}

Here is the client side JavaScript to make a Ajax Request.

function button_click(){

data={ “action”:”FunctionName“,“option”:”data to be passed” };
jQuery.post(ajaxurl,data,function(data)
{
var status=jQuery(data).find(‘response_data’).text();
var msg=jQuery(data).find(‘supplemental message’).text();
if(status==’success’)
{
alert(“Success:”+msg);
}
else
{
alert(“error:”+msg);
}
}
);

}

Well that’s it, we are done here :)

2 Responses so far.

  1. Marden says:

    Why do I bohter calling up people when I can just read this!

  2. Remarkable content. I have been previously looking at content pertaining to recent several weeks. Your lifestyle involving producing can be astounding i am definitely impressed. MY SPOUSE AND I is not going to always be moving past this information on our pals. I’m going to in addition always be book-marking your web site to ensure i’m able to usually go through your current blogposts. Carry on the excellent operate close friend. Wonderful go through.