How to do custom AJAX in a WordPress theme or plugin

How to do custom AJAX in a WordPress theme or plugin

WordPress does AJAX in a particular way and as such this article shows you how to do a generic AJAX call which you can alter as per your specific needs and can be added to your theme (child) or plugin code.

Table of Contents

What is AJAX?

AJAX stands for Asynchronous Javascript and is really just a term which describes the same set of web technologies (PHP, MYSQL, HTML, Javascript) used to render a normal web page BUT with a difference in timing.

Website software including WordPress usually renders content to the page on page load but what if you want to change the content on the site without reloading the page? Well that’s when you use AJAX.

With Javascript you do something like this,

  • Add some javascript to say something like ‘if you click on this button’ then do some PHP and MYSQL,
  • Then get the result of this PHP and MYSQL and return it to the page
  • Once we have this data on the page we can do something with it like present it to the user.

Commonly this is used for something like a search feature on a site which you type in, press submit and wait for results to be presented to you on the page. Something like this would be powered by AJAX in WordPress.

How does WordPress do AJAX differently?

WordPress, being its own particular software (framework perhaps), has its own ways of doing AJAX. As such you need to ‘do AJAX’ in a particular way in WordPress using particular hooks to add your Javascript to the page in a way which understands and knows what function to run exactly when a certain piece of javascript has been produced.

In the next section we will see how to code AJAX in WordPress.

Code to write an AJAX request in WordPress

We need to add both Javascript, PHP and potentially CSS to our WordPress Theme (or Plugin or Child Theme). But most of this takes place in PHP.

Step 1 – Add some PHP:

Find your functions.php file at something similar to https://yoursite.com/wp-content/themes/yourtheme/functions.php.

Then add the following code to the end of your functions.php

<?php
// the rest of your code in functions.php

function betterdevdocs_ajax_enqueue() {

	wp_enqueue_script(
		'betterdevdocs-ajax-script',
		get_template_directory_uri() . '/whereverYouStoreYourJS/betterdevdocs.js',
		array( 'jquery' )
	);

	wp_localize_script(
		'betterdevdocs-ajax-script',
		'betterdevdocs_ajax_obj',
		array(
			'ajaxurl' => admin_url( 'admin-ajax.php' ),
			'nonce' => wp_create_nonce( 'betterdevdocs-nonce' )
		)
	);
}
add_action( 'wp_enqueue_scripts', 'betterdevdocs_ajax_enqueue' );

To explain what this code is doing and how to use it,

  • The Javascript which will power your AJAX functionality needs to be ‘queued’ with all the other scripts which WordPress needs to load on its various pages. WordPress has a particular set of functions which allow you to do this and these are them.
  • ‘wp_enqueue_scripts’ is one of those particular functions and is called by WordPress to get all the scripts required for any particular page load.
  • In the above code we are adding our own Javascript file (with which in later steps we will add some specific AJAX related code) to the mix so that WordPress will understand to load it on the page.

Step 1.2 – Add some PHP

We then need to add some more PHP to our functions.php. Add the below code just after the code in Step 1.1 above.

<?php
// Existing PHP code in your functions.php
function betterdevdocs_ajax_request() { 
    // You can do any PHP code you like here and return the results    
    // The key/value pairs inside of the $_REQUEST array will contain the variables passed in form the AJAX request identified in step 3 below. So you could access anything you send through from JS by accessing something like $_REQUEST['myVariable']; - see step 3 code for more info on this.
    
    print_r( $_REQUEST );
    die();
}
 
add_action( 'wp_ajax_betterdevdocs_ajax_request', 'betterdevdocs_ajax_request' );

To explain the above code more,

  • This is the function which is run whenever our Javascript is triggered. The result of this function will be what is returned to the page and dealt with by the Javascript in step 3 of this tutorial.
  • NOTE: The key/value pairs inside of the $_REQUEST array will contain the variables passed in form the AJAX request identified in step 3 below. So you could access anything you send through from JS by accessing something like $_REQUEST[‘myVariable’]; – see step 3 code for more info on this.

Step 1.3 (optional) – Add some PHP:

There is one more piece of code which you can add dependent on the needs of your AJAX functionality.

The below code will allow the AJAX functionality above to be available to logged in and non-logged in users.

If you don’t add the below code then the AJAX will only work for logged in users. If your functionality is meant to be used by public (non-logged in) users also then add the below line.

If you decide to add this to the rest of the code in your functions.php file or indeed the plugin code if you are building a plugin.

<?php
// existing code in functions.php
add_action( 'wp_ajax_nopriv_betterdevdocs_ajax_request', 'betterdevdocs_ajax_request' );

Add some CSS (optional):

If you have specific CSS with which you want to be loaded which is related to the AJAX functionality you are creating you could add it as per the below.

NOTE: This is not necessary to make the AJAX work but do as your project dictates.

Add this code to your functions.php

<?php
// existing code in your functions.php

function betterdevdocsScripts() {
    wp_enqueue_style( 'bdd-css', get_stylesheet_directory_uri() . '/ajaxRelatedStyles.css', '', '', false );
}
add_action( 'wp_enqueue_scripts', 'betterdevdocsScripts' );

To explain what this code does,

  • We are adding some specific CSS to the page in ‘ajaxRelatedStyles.css
  • You can write whatever CSS you like and add it to this this file to support your AJAX functionality.
  • You can add this file to your theme or plugin or child theme in whichever file system structure you deem appropriate.
  • NOTE: Make sure to change this line ” get_stylesheet_directory_uri() . ‘/ajaxRelatedStyles.css’ ” to be accurate to wherever you stored this file. The above line is looking for a file at something like https://yoursite.com/wp-content/themes/yourtheme/jaxRelatedStyles.css but you may want to add it to a different folder.

Step 3 – Add some Javascript

Lastly we need to add some Javascript to our site to trigger and manage the above PHP functions.

Remember that in the above step 1.1 we enqueued a Javascript file by adding this line,

get_template_directory_uri() . '/whereverYouStoreYourJS/betterdevdocs.js'

Well now we need to add some Javascript (specifically jQuery) to this file which will trigger the PHP code we created above and also deal with it once it has completed and allow us to ‘do something’ when it returns our results.

So, add the below code to your ‘betterdevdocs.js’ file or whichever file you used in its place.

jQuery(document).ready(function($) {
    
    var myVariable = 'Replace me with some info from my front end that I want to send through to my corresponding betterdevdocs_ajax_request().';
    $.ajax({
        url: betterdevdocs_ajax_obj.ajaxurl,
        data: {
            'action': 'betterdevdocs_ajax_request',
            'myVariable' : myVariable,
            'nonce' : betterdevdocs_ajax_obj.nonce
        },
        success:function(data) {
            console.log(data);
            // do something useful here with the results returned from our php function betterdevdocs_ajax_request()
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });  
});

To explain this code a little more,

  • This code will be loaded on each page load WordPress makes in the front end.
  • When this script is loaded it will execute an AJAX call to our PHP function betterdevdocs_ajax_request() which we added in an above step.
  • When it does you can open up your console and you’ll see the $REQUEST details printed to the console because thats what our betterdevdocs_ajax_request() does.
  • NOTE: You could replace the code above representing ‘myVariable’ with your own data from your own application and theirfore it will be accessible in your PHP function.

Learn WordPress customization throughly with an online course at Udemy

If you are having difficulty understanding this tutorial and then I suggest you start from scratch with WordPress in general. The best way to learn is with a better all around general understanding of WordPress. Check out some of the courses on Udemy related to WordPress. They cover developer level courses and more non-dev CMS editor type tutorials as well.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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