How to Ajax

Load the script in plugin or theme

// enqueue the javascript
add_action('wp_footer', array($this, 'add_footer_script'));
// register the Ajax callback function
add_action('wp_ajax_add_to_cart_callback', array($this, 'add_to_cart_callback'));  
// and register it like this too
add_action('wp_ajax_nopriv_add_to_cart_callback', array($this, 'add_to_cart_callback'));

function: add_footer_script

 // (1)
 wp_enqueue_style('woocommerce-related-items-tab-css', CHILD_THEME_URL . ('/inc/woocommerce_related_items_tab.min.css'), false);
 // (2)
 wp_enqueue_script('woocommerce-related-items-tab-js', CHILD_THEME_URL . ('/inc/woocommerce_related_items_tab.js'), array('jquery'), null);

// (3)
wp_localize_script(
     'woocommerce-related-items-tab-js', 
     'woocommerce', 
     [
       'ajax_url' => admin_url('admin-ajax.php'),
       'other_var' => 'Johan is a nice guy'
     ]
);
  1. Loading CSS (not important for Ajax calls)
  2. Loading the Javascript containing the Ajax code (see below)
  3. Localizing the script, that is the handle is linked to a "namespace" woocommerce. At the moment of entering the javascript, the variables woocommerce.ajax_url and woocommerce.other_var become available.

Javascript code: woocommerce_related_items_tab.js

// global
let snackbar = null;

jQuery(document).ready(function ($) {
    // see for woocommerce.ajax_url the php script
    let ajaxurl = woocommerce.ajax_url,  // <------ from the wp_localize_script (see above)
        $this, form, qty, id,
        $body = jQuery(document.body);

    $body.on('click', '.single_add_to_cart_button.button.alt', function (e) {
        e.preventDefault();
        $this = jQuery(this);
        form = $this.closest('form');
        qty = form.find(':input').val();
        id = $this.attr("value");

        $this.button('loading');

        jQuery.ajax({
            type: 'post',
            data: {
                action: 'add_to_cart_callback', // <---- callback function (see below)
                quantity: qty,
                product_id: id
            },
            dataType: 'json',
            url: ajaxurl,
            success: function (data) {
                $this.button('reset');
                snackbar(data['message']);
                $body.trigger('added_to_cart');
            }
        });
    });

    snackbar = function (message) {
        // Get the snackbar DIV
        var x = document.getElementById("snackbar");
        x.innerHTML = message;

        // Add the "show" class to DIV
        x.className = "show";

        // After 3 seconds, remove the show class from DIV
        setTimeout(function () {
            x.className = x.className.replace("show", "");
        }, 3000);
    }
});

Callback function in PHP

This relates to what we described at the beginning:

add_action('wp_ajax_add_to_cart_callback', array($this, 'add_to_cart_callback'));  
add_action('wp_ajax_nopriv_add_to_cart_callback', array($this, 'add_to_cart_callback'));

The function:

public function add_to_cart_callback()
{
   $retval = array(
      'success' => false,
      'message' => ""
   );

   $product_id = $_POST['product_id'];
   $quantity = isset($_POST['quantity']) ? $_POST['quantity'] : 1;

   $cart = WC()->cart;
   $retval['success'] = $cart->add_to_cart($product_id, $quantity);

   if (!$retval['success']) {
      $retval['message'] = __("Product could not be added to cart", 'duobond');
   } else {
      $retval['message'] = __("Product added to cart", 'duobond');
      $retval['button_text'] = __('Added to cart', 'duobond');
   }

   echo json_encode($retval);
   wp_die();
}
Last update: October 25th at 11:57am