Published on

Making AJAX Requests in WordPress

This article will guide you on the basics of using AJAX request in WordPress. Before reading this article you should already know the following things:

  • Basic Guidelines on how ajax works.
  • Basics on Actions hooks
  • Basics on Jquery

Ajax can be used in multiple ways  but in WordPress it is a bit different and might get confusion at first. You can use in multiple ways also but there is one method that you should follow for few reasons. Ajax is integrated and pre-built in WordPress.

Introduction to AJAX ( Asynchronous Javascript and XML )

If you are not familiar with AJAX then i suggest you read this here. Ajax is simply the combination of HTML, CSS and javascript file that allows you to send the script, process it and get the data without needing to reload the webpage. There are numerous advantages of AJAX. To get the most out of the AJAX you will need to enhance and learn more on javascript and PHP.

How AJAX fits in with WordPress

Ajax is already built into the core WordPress. Basically, it has already been implemented for you. All you need to do is use the available function to trigger it.

In WordPress every ajax request goes through admin-ajax.php file in the wp-admin folder. Each request has to be supplied with a piece of data using a GET or POST request which is called action. If the action is not specified then the admin-ajax.php will return 0 and exit. When passed an action the admin-ajax.php file creates two hooks, wp_ajax_my_action and wp_ajax_nopriv_my_action, where my_action is the action.

Send AJAX Request

Create a seperate javascript file and add the following code.

jQuery(document).ready(function($) {
	var data = {
		'action': 'my_action',
		'whatever': 1234
	};
	
	jQuery.post(ajax_object.ajax_url, data, function(response) {
		alert('Got this from the server: ' + response);
	});
});

With the external javascript file we must first en-queue them in our functions.php file. Additionally we need to localize the properties in order to pass the JavaScript object properties.

add_action('admin_enqueue_scripts', 'enqueue_scripts');

function enqueue_scripts() {
       wp_enqueue_script( 'ajax-script', plugins_url( '/js/custom.js', __FILE__ ), array('jquery') );
      //Localizing our script
	wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ));
}

So, now we have localized our script and ready to process the php file.

Lets add the following in our functions.php file

add_action( 'wp_ajax_my_action', 'my_action_callback' );

function my_action_callback() {
        global $wpdb;
	$whatever = intval( $_POST['whatever'] );
	$whatever += 10;
        echo $whatever;
	wp_die();
}

In the above code the half part of wp_ajax_ i.e my_action should be the same action from our javascript file. The ajax request then processes the my_action_callback function and gives returns the data.

Remember, that we need to set wp_die() of every function that is hooked to ajax request. Otherwise, it will return a boolean value with it.

Similarly, in order to call ajax in frontend you will do the same procedure except we need to add one more hook while calling from frontend. Such as following.

 add_action( 'wp_ajax_my_frontend_action', 'my_frontend_action_callback' );
 add_action( 'wp_ajax_nopriv_my_frontend_action', 'my_frontend_action_callback' );

Error Return Values

If the Ajax request fails in wp-admin/admin-ajax.php, the response will be -1 or 0, depending on the reason for the failure. Additionally, if the request succeeds, but the Ajax action does not match a WordPress hook defined with add_action('wp_ajax_(action)', ...) or add_action('wp_ajax_nopriv_(action)', ...), then admin-ajax.php will respond 0