Using Ajax in WordPress

AJax stands for Asynchronous JavaScript and XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with server-side scripts. 

When we write Word Press Plugins, Ajax is sometimes necessary for us if we need to grab some data from server in our javascript from the browser.

Word Press provide admin-ajax.php in the wp-adim folder to help us dealing with Ajax request. There are two important hooks:

1. wp_ajax_nopriv_{$_REQUEST['action']}
2. wp_ajax_{$_REQUEST['action']}

The first hook is for visitors (without any administrator logged in). The second one is for administrators.

To deal an ajax request, we need to add some actions for the two hooks above. (assume that the action name is 'action-name')

add_action('wp_ajax_nopriv_action-name', 'visitor_ajax_callback');
add_action('wp_ajax_action-name', 'admin_ajax_callback');

Then complete the callback functions.

function visitor_ajax_callback () {
    //TODO
    $info = array (........);
    echo json_encode($info, JSON_UNESCAPED_UNICODE);
    wp_die();//This is required to terminate immediately and return a proper response
}

function admin_ajax_callback () {
    //TODO
    $info = array (........);
    echo json_encode($info, JSON_UNESCAPED_UNICODE);
    wp_die();//This is required to terminate immediately and return a proper response
}

In the browser side, we should add Ajax part into javascript.


$.ajax({
            url: ajaxUrl,
            type: 'post',
            dataType: 'json',
            data: {
                action: 'action-name'
            },  
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                console.log(textStatus);
            },  
            success: function (res) {
                console.log(res);
            }   

        }); 

After these steps, when the javascript is triggered, the server will send $info to the browser and the browser will get it in json and print it out.

评论

此博客中的热门博文

Openwrt路由器上配置shadowsocks透明代理+gfwlist(PAC)

Configure shadowsocks transparent proxy + gfwlist(PAC) on OpenWRT Router

Using Haproxy + shadowsocks (ha + ss) to setup multi ss backend and load balance