Sunday, 9 May 2021

Your AJAX Starter Kit, WordPress edition (Part 2/2)

I'm back!

Implementing AJAX, of course, requires a lot more than just JavaScript. We've done the front-end, now we need a back-end. AJAX in WordPress has its own implementation, via admin-ajax.php. To do this, we need to pass the URL of that location, like so.

plugins/tt_ajax_test/tt_ajax.php
<?php
/**
 * Plugin Name: AJAX Test
 * Plugin URI: http://www.teochewthunder.com
 * Description: This plugin implements and tests AJAX functionality
 * Version: 1.0.0
 * Author: TeochewThunder
 * Author URI: http://www.teochewthunder.com
 * License: GPL2
 */

function tt_ajax_listener() {
    wp_register_script( 'ajax_listener', plugin_dir_url( __FILE__ ) . '/js/tt_ajax_listener.js', ['jquery'] );
    wp_localize_script( 'ajax_listener', 'objAjax', ['ajaxurl' => admin_url( 'admin-ajax.php' )]);        

    wp_enqueue_script( 'ajax_listener' );
}

add_action( 'wp_enqueue_scripts', 'tt_ajax_listener' );


Then have some back-end code, defined in a function. In this case, it will take a string passed in via a POST, and use it as the format for a date() function. And most importantly, encode the output using json_encode(), then echo it.

plugins/tt_ajax_test/tt_ajax.php
<?php
/**
 * Plugin Name: AJAX Test
 * Plugin URI: http://www.teochewthunder.com
 * Description: This plugin implements and tests AJAX functionality
 * Version: 1.0.0
 * Author: TeochewThunder
 * Author URI: http://www.teochewthunder.com
 * License: GPL2
 */

function tt_ajax_listener() {
    wp_register_script( 'ajax_listener', plugin_dir_url( __FILE__ ) . '/js/tt_ajax_listener.js', ['jquery'] );
    wp_localize_script( 'ajax_listener', 'objAjax', ['ajaxurl' => admin_url( 'admin-ajax.php' )]);        

    wp_enqueue_script( 'ajax_listener' );
}

add_action( 'wp_enqueue_scripts', 'tt_ajax_listener' );

function tt_ajax_call() {
    $date = date($_POST['format'], strtotime('now'));
    echo json_encode(['date' => $date]);
    die();
}


After that,we use add_action() to add this function to the hooks wp_ajax_tt_ajax_call and wp_ajax_nopriv_tt_ajax_call, for logged in and anonymous access respectively. What happens is that every AJAX call is registered in a named variable at runtime, and we just did it for tt_ajax_call(). I'm aware that this isn't a great way of explaining it, but you get my drift...

plugins/tt_ajax_test/tt_ajax.php
<?php
/**
 * Plugin Name: AJAX Test
 * Plugin URI: http://www.teochewthunder.com
 * Description: This plugin implements and tests AJAX functionality
 * Version: 1.0.0
 * Author: TeochewThunder
 * Author URI: http://www.teochewthunder.com
 * License: GPL2
 */

function tt_ajax_listener() {
    wp_register_script( 'ajax_listener', plugin_dir_url( __FILE__ ) . '/js/tt_ajax_listener.js', ['jquery'] );
    wp_localize_script( 'ajax_listener', 'objAjax', ['ajaxurl' => admin_url( 'admin-ajax.php' )]);        

    wp_enqueue_script( 'ajax_listener' );
}

add_action( 'wp_enqueue_scripts', 'tt_ajax_listener' );

function tt_ajax_call() {
    $date = date($_POST['format'], strtotime('now'));
    echo json_encode(['date' => $date]);
    die();
}

add_action("wp_ajax_nopriv_tt_ajax_call", "tt_ajax_call");
add_action("wp_ajax_tt_ajax_call", "tt_ajax_call");


The AJAX call is pretty much what was presented in Your AJAX Start Kit, jQuery edition. For added security, we could implement a nonce, but I'm going with the bare minimum here. In here, we pass in a test string, to this URL. This references the function I just created in the backend. For data, I will pass in "j M Y H:i:s".

plugins/tt_ajax_test/js/ajax_listener.js
jQuery(document).ready(function(){
    if (window.location.href.indexOf("ajax-test") > -1) {
        jQuery('#btnAjax').click(()=>{
            jQuery.ajax({
                type : "post",
                dataType : "json",
                url : objAjax.ajaxurl,
                data : {action: "tt_ajax_call", format: "j M Y H:i:s"},
                success: function(data, textStatus, jqXHR) {

                },
                error: function(err) {
                    alert('Error');
                }
            });        
        });

    
        alert('test js');
    }
});


Once the data is returned, I populate the placeholder with the results. Oh yes, and I'll remove the earlier test command to remove the annoying pop-up.

plugins/tt_ajax_test/js/ajax_listener.js
jQuery(document).ready(function(){
    if (window.location.href.indexOf("ajax-test") > -1) {
        jQuery('#btnAjax').click(()=>{
            jQuery.ajax({
                type : "post",
                dataType : "json",
                url : objAjax.ajaxurl,
                data : {action: "tt_ajax_call", format: "j M Y H:i:s"},
                success: function(data, textStatus, jqXHR) {
                    jQuery('.tt_placeholder').html(data.date);
                },
                error: function(err) {
                    alert('Error');
                }
            });        
        });
    
        //alert('test js');
    }
});


Now click the button, and we should see the current date in the specified format. Every time you click, the format should change!


Finally!

That seemed simple enough.

AJAX isn't really that straightforward in WordPress. But now that I've documented which hoops to jump through, hopefully it's a lot easier from this point forward.

(Word)Press on,
T___T

No comments:

Post a Comment