WordPress Ajax

Ajax is used by wordpress for communication between browser and server. For example, after you login wordpress dashboard, drag a widget onto a sidebar, fill some settings and click the “Save” button, the settings of the widget instance will be sent back to the server using ajax call and stored into the wordpress database(please refer to this post). The wordpress ajax url is wp-admin/admin-ajax.php, which has been stored in a javascript variable ajaxurl to be used in your script. You can use this wordpress ajax url variable inĀ  frontend directly, no need to define it again.

To use ajax to deal with user action, you should create an action and hook an ajax handler function to the action to handle the ajax request.
add_action('wp_ajax_actionname', 'do_real_work');
Note that the action’s name must be of the form wp_ajax_xxxxx(admin ajx hook) or wp_ajax_nopriv_xxx(for logged out user).
In your client script, use the following ajax call:
jQuery.post(ajaxurl, {action: 'actionname', yourfield: 'yourvalue'}, function(data){}};

When admin-ajax.php receives the request, it gets the action name and does the corresponding action wp_ajax_actionname, and your customized function do_real_work will then be called to handle the ajax request.

Your do_real_work() can further get the customized fields from $_POST to do something useful.

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!

Leave a Reply