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.

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:

Leave a Reply