How to create an AJAX call in WordPress step by step

WordPress essentially works thanks to PHP language that gets the requests from users and admins, processes these requests and finally constructs the results as HTML pages, ie, PHP sends to you the pages that you see in the browser. Request, process, results; it’s simple. Sometimes however, you need control some elements of the screen after the HTML page has been sent and displayed: a special message on the screen after a checkbox has been checked, the change of an image depending on a select field, etc. and you don’t want to make a new request again. You want that these little elements change on the screen without repeat the whole process of request, process, results… In these cases you need to use the AJAX technique.

The first historical reference to AJAX technique (Roman Villa at Halicarnassus, 4th century AD)

Beyond this more than dubious historical reference of the previous illustration 🙂 , AJAX is a technology of developement supported by javascript and designed precisely for doing these kind of tasks, ie, to comunicate the client site to the server side silently, without a complete requests, just with the execution of a concrete funcion or module on the server side with a few concrete results. So it’s a fantastic alternative to make user web interactions more fluent and friendly (for an extense reference about AJAX you can consult the wikipedia page about this technique of developement ).

But before you start building an AJAX procedure, we must first see what elements are involved in this process.

The elements of an AJAX call in WordPress

Each one of the elements (parts) involved in an AJAX procedure, with little differences in their source code, are always the same; they always pursue the same objective, and always develop the same tasks. For this reason, it’s important to see and to explain previously these elements in detail because, if you do get the real meaning each element, from that moment, you’ll always construct easily any kind of AJAX call without any problem. The word is “always” because most of the AJAX procedures, structurally, are equivalent. So let’s go to see these elements one by one before seeing a concrete example.

Standard elements (parts) of an AJAX procedure

Basically, an AJAX procedure has always got three elements:

  • the HTML nodes of the screen, commonly the DOM (Document Object Model),
  • a javascript call function,
  • a remote server side function.

And, in the case of the WordPress environment, the AJAX procedure has also got a fourth element,

  • a link between the javascript call function and the name of the remote server side function.

If we see these elements (parts) on detail, we will realize that each one of them has always got the same structure, tasks, goals.

1 In the first place, we have the HTML nodes of the screen that the user can change usually through interactions with the keyboard or the mouse. On the other hand, each one of these HTML nodes has got a list of properties, events and states that are changed by these interactions of the user.

2 In second place, we have the javascript call function (in our case a jQuery function),

  • whose first section monitorizes the interactions of the user and registers the changes in the values, states, or events of the HTML nodes of the screen produced by these interactions,
  • whose second section creates an XMLHttpRequest call with the list of these changes, the dataValues (adding an WP actionName in case of WP),
  • whose third section will pick up the results of the XMLHttpRequest call when the server side executed functionName returns its results.
  • And whose last section will change the HTML Nodes of the screen for that they show these new results to user.

3 In the third place, we have got the remote server side function that, in the case of WP it’s identified by its functionName and,

  • whose first section picks up the dataValues sent by the XMLHttpRequest call,
  • whose second section processes these values and… Perhaps it makes a database query, or calls to another function, or whatever…,
  • and whose last section returns the results of the previous section to the javaswcript function and stops the remote server side execution.

4 And in the last place, we have the link between client and server sides so, in the case of WP, we have to inform to WordPress via the WP add_action function about that we want that when a concrete actionName were executed, the functionName has to be called.

See this scheme.

Scheme of elements and process flow in an AJAX procedure

Constructing a WordPress AJAX call step by step

In today’s example, we’re going to suppose that on the screen, we have got a select field with a list of our products and we want that depending on the change of this select field, an image of the product appears on the screen and, additionaly, we’re not going to construct the AJAX call with pure javascript but with jQuery.

1 – The HTML elements of the screen

The process for making an AJAX call begins on the client side so, once the page has already been displayed, on the client site we have only got the HTML elements of the browser so, these elements will be our starting point. An AJAX call almost always begins with the HTML elements of the browser.

On the screen we have got a select field like this, and additionaly, we have an HTML element that will contain the image of the product but now, this last HTML element is empty.

Take a look to its code

<label for="ProductNameID">Select your Product</label>
<select id="ProductNameID" name="ProductName">
    <option value="0">No product selected</option>
    <option value="2143">King size Table</option>
    <option value="2144">Big Table</option>
    <option value="3551">Medium Table</option>
    <option value="2145">Small Table</option>
    <option value="2847">Tiny Table</option>
    //... the rest of products.
</select>
<span id="productImageResult" ></span>

2 – The javascript function (jQuery)

As we have saw, the jQuery function has always got 4 sections. So our jQuery function to construct the AJAX call will begin taking the value of the select field but, taking into account that if we want that the image changes acording on the value of this field, we must take/check the value of the field each time that it changes. Perhaps, in the first section we could write a jQuery function that controls the change event for the field whose id attribute is ProductNameID.

jQuery(document).ready( function($) {
    var valueCheck;
    $('#ProductNameID').on( 'change', function () {
         valueSelect = $(this).val();
         // other sections in a few seconds
    });
});

With the value of this variable called valueSelect now, we’re goint to develop the second section of the jQuery function. To do this, we have to add a standard jQuery $.ajax() function call that contains the dataValues, in our example valueSelect, the name of the action that the remote execution of WP has to run and, of course, the remote URL that will start the remote execution of the WP in the Server Side.

jQuery(document).ready( function($) {
    var valueCheck;
    $('#ProductNameID').on( 'change', function () {
         valueSelect = $(this).val();
         if ( parseInt ( valueSelect ) > 0 ) {
		$.ajax( 
                     ajaxurl, // The remote URL address that starts the remote execution of WP
                     {
			type: 'POST',                       // you can choose among any of HTTP request methods
			data: { action: 'getImageProduct', // The name of the WP action
				value:	valueSelect,       // The dataValues
                                // if you need it, other dataValues as elements of the object data
			},
			dataType: 'json', // we inform that we are going to receive PHP results as a JSON array
                        // ... other parameters for configuring the AJAX call if you need it

                        // Here the third section

		    });
         }
    });
});

Now, we have to develop the third section where we’ll get the JSON array of results sent by the remote PHP called function by the remote execution of the WP. And we’re goint to suppose the this remote PHP funcion sent us and array with this structure.

array {
    success => boolean // [ TRUE, FALSE ], 
    html    => string  // something like: <img scr="etc...." >
}

So, the third section will be like this

jQuery(document).ready( function($) {
    var valueCheck;
    $('#ProductNameID').on( 'change', function () {
         valueSelect = $(this).val();
         if ( parseInt ( valueSelect ) > 0 ) {
		$.ajax( ajaxurl, {
			type: 'POST',
			data: { action: 'getImageProduct', // The name of the WP action
				value:	valueSelect,       // the dataVAlues
			},
			dataType: 'json',
			complete : function ( response ) {   // to develop always
                        }, 
			success: function ( response ) {     // to develop in case of correct AJAX call
                             if ( response.success ) {
                                  image = response.html;  // Here we get the results of the PHP remote function
                                  // The code for other results in the JSON object response

                                  // Here will write the Last section

                             } else {
                                  // code in case of image error
                             }
                        },
			error: function ( errorThrown ) {   // to develop in case of AJAX call error
                             console.log( errorThrown ); 
                        }, 
		});
         }
    });
});

And finaly, in the last section we’ll introduce the PHP remote function results in the HTML elements of the screen so, we have to put the response.html inside the span whose id is productImageResult. See the complete code of the jQuery function.

jQuery(document).ready( function($) {
    var valueCheck;
    $('#ProductNameID').on( 'change', function () {
         valueSelect = $(this).val();
         if ( parseInt ( valueSelect ) > 0 ) {
		$.ajax( ajaxurl, {
			type: 'POST',
			data: { action: 'getImageProduct', // The name of the WP action
				value:	valueSelect,       // the dataVAlues
			},
			dataType: 'json',
			complete : function ( response ) {   // optionally to develop in any case: success or error
                        }, 
			success: function ( response ) {     // to develop in case of success
                             if ( response.success ) {
                                  image = response.html;  // Here we get the results of the PHP remote function
                                  $('#productImageResult').html( image );
                             } else {
                                  $('#productImageResult').html( '<span>No image available for product #id: ' +  valueSelect + '</span>' );
                             }
                        },
			error: function ( errorThrown ) {   // to develop in case of error
                             console.log( errorThrown ); 
                        }, 
		});
         }
    });
});

3 – The remote server side function

This part has also got the same structure always. In the first section the function picks up the values sent by the XMLHttpRequest and the simplest way to do it is using the $_POST PHP vars. So the first section of our remote function could be like this.

function myImagesSelector () {
     $id = $_POST['value'];
     // $color = $_POST['color'];  // you can get other var if you need it
     // etc.

     // Here the second section

}

The second section is the main task of the remote PHP function. Here is where you can develop your database request, or call to another function, or whatever. For this example, we develop a simple switch that retrieve the correct image URL associated with each one of the product #id’s.

function myImagesSelector () {
     $id    = (int) $_POST['value'];

     $image = '';
     switch ($id) {
         case 2143:
        case 2144:
              $image = '<img src="http://mysite.com/products/' . $id . '/images/' . $id . '_bordered_big.jpg" >';
              break;
         case 2145:
              $image = '<img src="http://mysite.com/products/' . $id . '/images/product_big.jpg" >';
              break;
         case 2847:
         case 3551:
              $image = '<img src="http://mysite.com/products/' . $id . '/images/' . $id . '_00.jpg" >';
              break;
         // other cases
         default:
              // No image;
     }

     // Here the third section


}

And finally we add the last section, where we echoes the results as a JSON array, adding if the remote procedure is OK.

function myImagesSelector () {

     // third section in case of error
     if ( isset ( $_POST['value'] ) ) {
          $results['success'] = FALSE;
          $results['html']    = '';
          echo json_encode ( $results );
          die();
     }

     $id    = (int) $_POST['value'];
     $image = '';
     switch ($id) {
         case 2143:
         case 2144:
              $image = '<img src="http://mysite.com/products/' . $id . '/images/' . $id . '_bordered_big.jpg" >';
              break;
         case 2145:
              $image = '<img src="http://mysite.com/products/' . $id . '/images/product_big.jpg" >';
              break;
         case 2847:
         case 3551:
              $image = '<img src="http://mysite.com/products/' . $id . '/images/' . $id . '_00.jpg" >';
              break;
         // other cases
         default:
              // No image;
     }

     // Third section in case of success
     $results['success'] = TRUE;
     $results['html']    = $image;
     echo json_encode ( $results );
     die();

}

4 – The link between client and server sides. add_action

In the case of WP, if we want to use its AJAX API for creating our calls, we have to add a final line where we explain to WP that we want to run the remote function inside a concrete action so that basically add_action( actionName, functionName ).

However, in case of AJAX requests, WP has got his own API so firstly, we have to distinguish between web user interface requests and WP admin interface requests because each one of them has got a different associated action names.

And secondly, we can’t use our actionName directly but we have to add a preffix to the actionName. See this two examples.

If our remote function name is myImagesSelector and our action name is getImageProduct, in the case of an AJAX call made from the WP admin interface we have to add this code line to construct the link:

add_action ( 'wp_ajax_' . 'getImageProduct', 'myImagesSelector' );

And in the case of an AJAX call made from the web user interface we have to add this code line

add_action ( 'wp_ajax_nopriv_' . 'getImageProduct', 'myImagesSelector' );

Of course, we can add both of lines if we want to be able to execute our remote function from both interfaces.

add_action ( 'wp_ajax_' . 'getImageProduct', 'myImagesSelector' );
add_action ( 'wp_ajax_nopriv_' . 'getImageProduct', 'myImagesSelector' );

Some final thoughts

Remember that we have to add the javascript function file to the WP theme using the wp_enqueue_scripts action.

Remember that, in case of AJJAX call from plugins, this last element (the add_action lines) has to be included in the main file of the plugin otherwise it doesn’t work.

Remember that any echo or screen print inside the remote function will be captured by the client side javascript function.

Remember that during the remote execution of the WP thanks to the AJAX call, not all modules are loaded so, it’s possible that you have to use the PHP require_once() function for including the functions or modules that you need.

And don’t forget to add always the correct prefix to your actionName, and finish your remote function with die().

The first image is just a joke, a derived work made for me from this former work: Part of a panel from a mosaic pavement- Atalanta, on horseback hunts a lion, from a Roman Villa at Halicarnassus, 4th century AD, British Museum (17405498930) by Carole Raddato from FRANKFURT, Germany on Wikimedia Commons licensed as [CC BY-SA 2.0 (http://creativecommons.org/licenses/by-sa/2.0)]

Have a nice WordPressing!

4 Comments on How to create an AJAX call in WordPress step by step

  • Thank you very much for this, this has saved me a lot of trouble I have been in for a couple of days trying to get wordpress to work with AJAX & jQuery…

    Only thing you should adjust is:
    function myImagesSelector {
    into:
    function myImagesSelector() {

    But thanks again, did a nice job, still need to tweak the script for my usage but will figure it out.

  • Is there any requirement that jQuery must be used to invoke ajaxurl?

    I don’t think I’ve seen one example on the internet where jQuery is not used.

    I’ve tried to see if regular javascript ajax call (w/o jQuery) will be honored inside the theme but that doesn’t seem to work.

    Would you have any insight?

Leave a Comment

   Mandatory field
You can use these HTML tags inside the commment.
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>