Making it AJAX

It's very easy to make add to cart work ajaxified. Here is simple tutorial to show you how.

As you probably already know, adding "add to cart" button into your templates is pretty easy:

$modules->get("PadRender")->addToCart($product, $askQty = true);

This adds pretty verbose markup for the button (it uses ProcessWire's inputfields, looking for a way to make it shorter), but that is "full featured" - meaning if you add modifiers there, it will also validate those nicely. By default add to cart process is simple:

  1. Customer clicks button and form submits
  2. Form is validated (modifiers are valid, no zero or negative amount of products added etc)
    1. If not valid, form is rendered again with error messages
    2. If valid, then product is added into cart and customer is redirected back to current page with cart updated, and productId=123 as a get param (where 123 is id for the added product).

To ajaxify this whole process we need to submit the form with ajax. Form can be submitted as is and Padloper will return results as JSON. Here is complete jQuery example to ajaxify the add to cart buttons:

// jQuery example of how to make add to cart buttons ajaxified
$( ".padloper-cart-add-product" ).submit(function( event ) {

  var $form = $(this);
  var url = $form.attr("action");

  // Send the data using post
  var posting = $.post(url, $form.serialize());

  posting.done(function(data) {
    if (data.errors) {
      var str = '';
      $.each(data.errors, function(i, val) {
        str = str + val;
    } else {

That example will do few things: if add to cart fails, it alerts the error message. There might be two reasons: form wasn't valid (probably due required modifier missing) or the product is out of stock. In case of success, it will update few html elements (#totalQty, #numberOfTitles and #totalAmount) with the updated values from your cart. Those elements you should add into your template markup.

Padloper newsletter

To get occasional updates about new features and discounts