Ajax in WordPress

AJAX is already used in WordPress’ back end. Every AJAX request goes through the admin-ajax.php file in the wp-admin folder.  Each request needs to supply at least one piece of data (using the GET or POST method) called action. Based on this action, the code in admin-ajax.php creates two hooks, wp_ajax_my_action (for logged-in users) and wp_ajax_nopriv_my_action (for logged-out users), where my_action is the value of the GETor POST variable action.

Here’s a simple plugin to demonstrate the concept. Just copy the code below and save a php file in your wordpress plugin folder. Then create a page and add the shortcode [SIMPLE_AJAX] to the content and view the page. You should see a button and when you click it the text of

would change from ‘Click button’ to ‘Result: Apple’.

Continue reading