Web Development WordPress

WordPress: How to send an AJAX call with JQuery and PHP

Several of the webpages and plugins that I have made with WordPress needed to update the database in some way or reference PHP on a button click. Since PHP and access to the database are run before page load, that seems impossible. This need to run PHP on as a response to user input when a button is pressed is exactly the case that an asynchronous AJAX call like the one I am about to show you comes in handy. Making this asynchronous call work is a multi-step process, but when it works it will do exactly what you want it to do.

First, in functions.php file, enqueue the script as normally but localize the script with a nonce which we will use for security purposes later:

Then in the JQuery file, use create a handler for a user clicking a button and in the response include a $.ajax call, which is the asynchronous part. Also in the JQuery we are sending the AJAX to the ajax_url that we localized into the script and we also pass the nonce for use in the PHP for security purposes:

And finally in the PHP file, add both actions listed below with the prefixes wp_ajax_ and wp_ajax_nopriv for users of different types, define the function using the same name used in the JQuery and get any data sent from the JQuery from post variables. One of those bits of data is the nonce, it is used to verify that your code sent the command and not some malicious actor. From here you can update the WordPress database and then optionally send results of the update back to the JQuery:

Leave a Reply

Your email address will not be published. Required fields are marked *