Notes for using Ajax in WordPress

While in WordPress admin area..  the variable named ajaxurl is available for javascript scripts to use for the url for ajax. Every call must at the very least have an “action” data property passed to WordPress in order for it to know which function will be used on the back-end to complete the ajax request.

The associated php that would be needed to process above :

Any ajax request must be handles by a function which has to be added via add_action

Note that any action you specify in the ‘action’ field for the data sent to the server will have ‘wp_ajax_’ prepended to the actions name.

Also need to bind to the action prefix ‘wp_ajax_nopriv’ so that the ajax will still work for visitors who are not logged in.

So the action ‘method_that_handles_the_ajax_request’ will have to be added in php as ‘wp_ajax_method_that_handles_the_ajax_request’ as seen in the php snippet.

If the action can not be found by admin-ajax.php the response returned from the ajax request will be an integer of zero ( 0 ).

If you created an ajax action method properly and you keep receiving a 0 response…confirm that your ajax action method was added.

Any function in php that handles a ajax request MUST end with die();

Within the php function, any post variable that is passed via the ajax data field, in our case the ‘address’ or ‘action’ field, is available via $_POST[“address”] or $_POST[“action”]


wp_localize_script

Used to add data to javascript that is normally only available on server side. Has to be used after an enqueue of a script and use the same “handle”. It will make the variables passed via localize_script available to the rest of the javascript that was enqueued.

Typically, this is used for nuances

Example of adding the nuances

Another way to add it when there are times where an additional script isn’t needed could be done in the following way.

 

 

 

Now we can update the javascript to use the nonce to pass back to WordPress to check for nonce validity.

Now that the nonce is created and is being passed from javascript to WordPress.. we setup below in php in the action that the ajax requests  to process it’s integrity.

 

Good notes for ajax usage: https://developer.wordpress.org/plugins/javascript/enqueuing/

 check_ajax_referer( 'nonce' );  This function will check nonce and if it fails will automatically kill the action it was ran within

 wp_send_json() will send back appropriate header and json back to javascript as well as wp_die() for the action it was called in.