How to use AJAX, jQuery in WordPress Plugin

Introduction

We will discuss here how to use AJAX in WordPress plugin. We will use the same plugin we created in the example. We have seen how to create MySQL table in our previous tutorial. This example will also show you how to en-queue JavaScript files. Till now our simple email subscription form could not perform any action but in this example we will use AJAX technique with jQuery so that users will be allowed to subscribe to the posts.

WordPress provides wp_enqueue_script() function for en-queuing the JavaScript files.

This function links a script file to the generated page at the right time according to the script dependencies, if the script has not been already included and if all the dependencies have been registered.

You could either link a script with a handle previously registered using the wp_register_script() function, or provide this function with all the parameters necessary to link a script.

This is the recommended method of linking JavaScript to a WordPress generated page.

Prerequisites

Make sure you read first on creating MySQL table for WordPress plugin tutorial.

Creating JavaScript File

It is always good practice to put the files into different folder instead of in the plugin’s root folder.

So we will create a JavaScript (js) file called roytuts-email-subscription.js under js directory. Of course your js directory should be kept under your plugin’s root folder.

The source code of the js file is given below:

jQuery(document).ready(function($) {
	jQuery('#roytuts_submit').click(function(e) {
		e.preventDefault();
		
		var email = jQuery('#roytuts_contact_email').val();
		
		var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/i;
		
		if(email !== '' && regex.test(email)) {
		
			var data = {
				'action': 'roytuts_email_subscription',
				'email': email
			};
			
			jQuery.post(ajax_object.ajaxurl, data, function(response) {
				if(response == "success") {
					jQuery('#roytuts-msg').html('<span style="color: green;">Subscription Successful</span>');
				} else if(response == "error") {
					jQuery('#roytuts-msg').html('<span style="color: red;">Subscription Failed</span>');
				}
			});
		} else {
			jQuery('#roytuts-msg').html('<span style="color: red;">Invalid Email</span>');
		}
	});
});

The above js file has simple code. When user enter email to the subscription form and click on the Submit button, we validate the email address using regular expression. This regular expression may not be a rigid one but it works.

Next we post the data to the server side and these data are action name and email address.

The action name is the callback function which gets fired in the PHP file of the WordPress plugin. We will see later how to write this function.

Depending upon the response coming from the server we are showing messages in different color – green for success and red for error.

There is one important variable passed to the post() method of jQuery function – ajax_object.ajaxurl. As we cannot directly call URL in WordPress as we do normally in PHP, so we have to define URL in a variable to call the callback function. We will also discuss on this later when we will en-queue the js file using wp_enqueue_script() function.

Enqueuing JavaScript File

Now we will enqueue the above js file. The enqueuing code should be kept into the plugin’s main PHP file.

add_action('wp_enqueue_scripts', 'roytuts_enqueued_assets');

function roytuts_enqueued_assets() {
	wp_register_script('ajaxHandle', plugin_dir_url( __FILE__ ) . '/js/roytuts-email-subscription.js', array('jquery'), false, true);	
	wp_localize_script( 
		'ajaxHandle',
		'ajax_object',
		array( 'ajaxurl' => admin_url('admin-ajax.php') ) 
	);
	wp_enqueue_script('ajaxHandle');
}

In the above code we have defined action hook to for our custom function that en-queue js files.

We register our js file using wp_register_script() function.

The first parameter is the name of the handler, second parameter is our js file.

Third parameter indicates that jquery library is required for our js file and needs to be loaded.

Fourth parameter indicates version of the js file and fifth parameter indicates whether the js file should be included into header or footer. true means in the header and false means in the footer.

Notice how did we define ajax_object and ajaxurl variables.

In WordPress, all AJAX requests are sent to admin-ajax.php file for processing the requests. This file resides within the /wp-admin directory of your WordPress site. Even though the file resides in the admin area of your site, you can still use it to process interactions from the front-end as well as back-end.

Handling AJAX Request

We previously mentioned the callback function which is mapped to the action name. Here we will see how it works.

We used the action name as roytuts_email_subscription which is being passed from your js file. The action parameter roytuts_email_subscription is responsible for making the connection between the JavaScript file and the PHP code. Therefore the full name of the action in WordPress will be wp_ajax_roytuts_email_subscription.

Generally users who visit your site will not login to your admin area and they will just enter email and click on Submit button to subscribe.

Therefore for non-logged in users you need to add another action – wp_ajax_nopriv_roytuts_email_subscription for AJAX working from front-end.

For more information on AJAX with WordPress plugin you can read here.

Below code does the required things to store user subscription information into MySQL table.

function roytuts_email_subscription_callback() {
	global $wpdb;
	
	if(isset($_POST) && !empty($_POST['email'])) {
		$email = $_POST['email'];
		$table_name = $wpdb->prefix . 'roytuts_email_subscribers';
		$fetch_sql_query = "select * from " . $table_name . " where email_id='$email'";
		$result = $wpdb->get_results($fetch_sql_query);
		if(count($result) == 0) {
			//Insert new row
			$data = array('email_id' => $email);
			$result_check = $wpdb->insert($table_name, $data);
			if($result_check){
				echo 'success';
			} else {
				echo 'error';
			}
		} else {
			echo 'success';//already subscribed
		}
	}
	wp_die();
}

add_action('wp_ajax_roytuts_email_subscription', 'roytuts_email_subscription_callback');
add_action('wp_ajax_nopriv_roytuts_email_subscription','roytuts_email_subscription_callback');

In the above code we first check whether the user already exists in the table and if does not exist then only we store into the table.

Hope you got idea how to create WordPress plugin, how to create table and store data into table in WordPress plugin and how to use AJAX in WordPress plugin.

Source Code

Download

2 thoughts on “How to use AJAX, jQuery in WordPress Plugin

  1. Thanks for this very useful tutorial. Only, the code you supplied doesn’t work. In the funtion function roytuts_email_subscription_callback() ou use another table name than when you created it. You create ‘roytuts_email_subscribers, and later you use ‘roytuts_subscribers’. Change that and it works like a charm, thanks!

Leave a Reply

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