AJAX page interactions are powered by JavaScript code and allow users to create pages with content that gets dynamically updated. To add this functionality to our bug tracking system, we start this recipe by modifying the existing shortcode bug query to only retrieve entries that have an open status (value of 0).
Once this is done, we move on to add two new elements to the initial shortcode output, a link to display closed bugs and a block of JavaScript code. The link itself is quite simple, containing a class name and a text label that visitors will be able to click. The JavaScript code is a bit more complex. Essentially, the script makes a request for the replacecontent function to be called when the show_closed_bugs link is clicked by visitors. In turn, the replacecontent function contains a single call to the jQuery ajax function. This function takes a number of arguments, starting with the type of operation, which is set to POST. This indicates that all the variables sent in the request URL will be stored in a standard $_POST variable array.
The second parameter is the URL to which the request should be sent. The variable used here is defined in the header code that is generated by the ch8bt_declare_ajaxurl function and points to the WordPress admin-ajax.php script URL. While the name of this script starts with the word admin, it can also be used to process AJAX requests from visitor-facing pages.
After these first two arguments is a data array that contains a number of data elements, such as the name of the action, a nonce field to secure the request, and the status of the bugs that should be retrieved. Finally, the success parameter indicates that the data received back from the AJAX request should be used to replace the HTML content of the bug-tracker-list div section of the existing page.
To process this request, our plugin goes on to register the function ch8bt_buglist_ajax to be called when one of two variable name actions are matched: wp_ajax_<actionname> or wp_ajax_nopriv_<actionname>. In both cases, <actionname> is the string that was sent as part of the data parameters in the AJAX request. Upon receiving the request, the callback generates an updated bug table, echoes the resulting HTML code, and makes a call to the standard PHP die() function. While this last step might seem strange, it is needed to avoid having a trailing 1 at the end of the new HTML, indicating that AJAX processing was successfully performed by WordPress.
While the ch8bt_buglist_ajax function shares a lot of code with the existing ch8bt_shortcode_list function, it is easier to create a separate code block that only contains the necessary elements for this example. That being said, combining the two functions would make future updates to the table layout easier to maintain.