Personal tools
You are here: Home Leocornus leocornus.tracclient How AJAX Work in WordPress

How AJAX Work in WordPress

The step by step guide to use AJAX on WordPress:

What's the Scope

We will using AJAX in different sections of a WordPress site. It could be the following sections:

  • Admin Panel, dashboard
  • A theme
  • A Plugin

Also, we may usie AJAX from different perspectives. It will be one the following:

  • Anonymous user
  • Authenticated user
  • Authorized user

The Very First AJAX Request

AJAX requests in WordPress are all processed by admin-ajax.php. The popular WordPress action/hook mechanism is used for each single request. Except the action name has special prefix wp_ajax_ and wp_ajax_nopriv_. The action with nopriv will be available for anonymous users.

The action name after wp_ajax_ and wp_ajax_nopriv_ should be consider as a regular WordPress action name. It should be unique. Otherwise, it might NOT be executed. So the best practise is using the prefix for the action name.

The following is a very easy example:

  • The PHP on server side. It could be in a plugin.
    /**
     * The PHP file in a plugin.
     */
    add_action('wp_ajax_myrequest', 'myrequest');
    add_action('wp_ajax_nopriv_myrequest', 'myrequest');
    function myrequest() {
    
        $response = array(
            'message' => 'hello AJAX'
        );
    
        echo json_encode($response);
        // exit is required!
        exit;
    }
    
  • The JavaScript on a page, theme page templage, widget, etc. The function admin_url will make sure the right URL for admin-ajax.php.
    <input type="button" onclick="javascript: showMyrequest()" 
      name="My Request" value="My Request"/>
    
    <script type="text/javascript" charset="utf-8">
    <!--
    function showMyrequest() {
    
        var data = {
            "action" : "myrequest",
        };
    
        jQuery.post("<php echo admin_url('admin-ajax.php'); ?>", 
            data, 
            function(response) {
    
                alert('got from server: ' + response);
            });
        }
    -->
    </script>
    

References

Tracking History

When Who What Done
2012-06-25 08:26 Sean Chen got good understanding about how AJAX work in WordPress. it is quiet easy and strait forward.
-- 3.0 Hours, 100.0% Done
Document Actions