WordPress Plugin with Ajax and MySQL
I wanted to follow up from my last post on building a WordPress Plugin Admin Page and write about using Ajax calls with WordPress plugins. It is very common nowadays to use XMLHttpRequest to move data from the front-end to the back-end and WordPress supports this very well. Consider a contact form on your blog, when someone hits submit you could initiate an Ajax request to your plugin and process the data. Today, I will show how to use Ajax with a WordPress plugin and I will build a complete Quick Contact WordPress plugin that stores a form submission to a new database table which is displayed for quick viewing on a new admin page.
First, let’s create the new database table and delete it when the plugin is uninstalled. Also, I wrote a simple contact form in a function of my WordPress plugin so that it is flexible and the user can drop the contact form in a specific place. I am using the Shortcode API so that a user can either drop the form into a specifc page with brackets([qc_form]) or use the function name (
echo function_qc_form();) inside the theme files:
Now, a form normally passes the data server side so we need to tie a client side listener to the form submission and overwrite it with an Ajax request. It could just be a form onsubmit event with a function that passes form data to the plugin. On the plugin side, we need a function that will be hooked into this request. Take a look at the code:
We have defined the WordPress Ajax url as
admin_url("admin-ajax.php") and in the data we put the function reference under action. This makes sure to send the data from front end to our plugin function which retrieves the name, email, and message, and sends it over to the mySQL database using
$wpdb->insert. Please notice the wp_ajax_(action) reference and see how I added wp_ajax_nopriv_(action) pointing to the same function. This is necessary to process Ajax requests from non-registered users.
The final step is to visualize the data in a special plugin page on the Admin side. I have covered this previously in my WP Plugin Admin Page post and the same instructions apply here. I altered it to use our quick contact table in HTML with the dataTables jQuery plugin.
Here is the final Quick Contact WordPress Plugin which shows how simple it is to use Ajax with a custom mySQL table in WordPress.
Ajax in WordPress