In MyCashflow, you can add products to the shopping cart by using AJAX calls. This article describes how to add products to the shopping cart from a product page and directly from product lists.

Introduction

Product purchase tools are printed with the {ProductAddToCart} tag on product lists, and with the {ProductBuy} tag on the product page. Each tag produces different HTML markup, so adding products to the shopping cart with Javascript takes place in different ways for each of them.

This article describes how to add products to the shopping cart both from product lists and from product pages. For both of these cases, we provide a JavaScript example, which you can copy to your theme and modify to suit your needs.

In both of the examples in this article, the page also has a shopping cart preview that uses the {MiniCart} tag:

<div class="MiniCartContainer">
    {MiniCart}
</div>

It is included in the examples because it's a good idea to update your shopping cart without any extra page reload whenever products are added to your shopping cart by using AJAX requests.

Add products with the default theme's Cart plugin

In MyCashflow’s Barebones default theme, adding products to the cart is provided through the AJAX-based cart.js plugin. You can customize how the plugin works with hook functions.

Adding products from a product page

Below you can see the HTML code of the purchase form {ProductBuy}:

<form action="/cart/" enctype="multipart/form-data" method="post" class="BuyForm">
    <fieldset>
        <input type="hidden" name="products[0395][product_id]" value="29" class="HiddenInput">
        <div class="FormItem BuyFormQuantity">
            <label for="BuyFormQuantity-0395">Quantity:</label>
            <input type="number" id="BuyFormQuantity-0395" name="products[0395][quantity]" size="3" min="0" value="1">
        </div>
        <div class="FormItem FormSubmit">
            <button type="submit" class="SubmitButton AddToCart"><span>Add to cart</span></button>
        </div>
    </fieldset>
</form>

In the example, the serializeObject() function is used to convert the form to a format that can be processed on the server. You can copy the code below to add the function to your scripts:

$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
    	if (o[this.name]) {
    		if (!o[this.name].push) {
    			o[this.name] = [o[this.name]];
    		}
    		o[this.name].push(this.value || '');
    	} else {
    		o[this.name] = this.value || '';
    	}
    });
    return o;
};

Send the product's purchase form to the server with a POST request. You can do it by using e.g. the jQuery ajax() function.

/*
* Adding is performed by clicking
* the submit button on the purchase form.
*/
$(".BuyForm .AddToCart").on("click", function(event) {
	event.preventDefault();

	/*
	* The purchase form is saved
	*/
	var $form = $(this).closest(".BuyForm");

	/*
	* A POST request is sent
	*/
	$.ajax({
		type: "POST",
		url: "/cart",

		/*
		* The serializeObject function is used to format the data on the server
		* into processable form.
		*/
		data: $form.serializeObject(),
		success: function() {

			/*
			* Finally, the shopping cart is updated after the product has been added.
			*/
			$.ajax({
				type: "GET",
				url: "/interface/MiniCart",
				success: function(data) {
					$(".MiniCartContainer").html(data);
				}
			});
		}
	});
});

In the ajax() function's settings parameter, a callback function could also be configured for the sake of an unsuccessful request. The beforeSend attribute can be used to validate the values entered into the form.

Adding products from product lists

Adding products to a shopping cart with JavaScript directly from product lists works according to a different logic because the {ProductAddToCart} tag used in lists does not print a form, but just a link to the product page:

<a href="/product/29/pants" title="Add to cart" class="Button AddToCart">
    <span>Add to cart</span>
</a>

To add a product to the shopping cart directly from a product list, the product's ID number must be extracted from the link's destination address. After that, the product can be added to the shopping cart by using its ID:

/*
* Adding products from lists
*/
$(".Product .AddToCart").on("click", function(event) {
	event.preventDefault();

	/*
	* First, the clicked link and the product element around it are saved
	*/
	var $link = $(event.currentTarget);
	var $product = $link.closest('.Product');

	/*
	* Based on the class name of the product element, you can see whether it has variations, customizations, or downloadable files.
	*
	* If so, the visitor is directed to the product page to make the necessary choices to add the product to the shopping cart.
	*/
	if ($product.hasClass('ProductVariations') || $product.hasClass('ProductTailorings') || $product.hasClass('ProductDownloads')) {
		window.location.href = $link.attr('href');
	}

	/*
	* Otherwise, the product is added directly from the list to the shopping cart.
	*/
	else {

		// The productID is extracted from the link
		productID = $link.attr('href').split('/')[2];

		// A POST request to add the product to the shopping cart is sent.
		$.ajax({
			type: "POST",
			url: "/cart",

			/*
			* A JSON object is sent as the request's content, where only the
			* product ID is needed.
			*/
			data: { products: [{ product_id: productID }] },
			success: function() {

				/*
				* After a successful request, the shopping cart is updated.
				*/
				$(".MiniCartContainer").empty();
				$.ajax({
					type: "GET",
					url: "/interface/MiniCart",
					success: function(data) {

						$(".MiniCartContainer").html(data);
					}
				});
			}
		});
	}
});

You can implement multiple functions connected to purchasing by using asynchronous JavaScript calls. Read also the following articles about asynchronous actions: