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.

Adding products in the default theme

In MyCashflow's default theme, adding products to the shopping cart has already been implemented by using an AJAX function.

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.

/*
* Suoritetaan lisääminen ostoslomakkeen lähetyspainikkeen
* klikkauksella.
*/
$(".BuyForm .AddToCart").on("click", function(event) {
	event.preventDefault();

	/*
	* Otetaan talteen ostolomake
	*/
	var $form = $(this).closest(".BuyForm");

	/*
	* Lähetetään POST-pyyntö
	*/
	$.ajax({
		type: "POST",
		url: "/cart",

		/*
		* Käytetään serializeObject()-funktiota muotoilemaan data
		* palvelimella luettavaan muotoon.
		*/
		data: $form.serializeObject(),
		success: function() {

			/*
			* Lopuksi päivitetään ostoskori tuotteen lisäämisen jälkeen
			*/
			$.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();

	/*
	Ensin otetaan talteen klikattu linkki ja sen ympärillä oleva tuote-elementti
	*/
	var $link = $(event.currentTarget);
	var $product = $link.closest('.Product');

	/*
	* Tuote-elementin luokkanimien perusteella nähdään, onko sillä variaatioita, räätälöintejä tai ladattavia tiedostoja.
	*
	* Jos niitä on, ohjataan kävijä tuotesivulle tekemään tarvittavat valinnat, jotta tuotteen voi lisätä ostoskoriin.
	*/
	if ($product.hasClass('ProductVariations') || $product.hasClass('ProductTailorings') || $product.hasClass('ProductDownloads')) {
		window.location.href = $link.attr('href');
	}

	/*
	* Muuten lisätään tuote suoraan listalta ostoskoriin.
	*/
	else {

		// Poimitaan tuotteen ID linkin osoitteesta
		productID = $link.attr('href').split('/')[2];

		// Lähetetään POST-pyyntö, jolla tuote lisätään ostoskoriin.
		$.ajax({
			type: "POST",
			url: "/cart",

			/*
			* Pyynnön sisältönä lähetetään JSON-objekti, jossa tarvitaan vain
			* tuotteen ID.
			*/
			data: { products: [{ product_id: productID }] },
			success: function() {

				/*
				* Onnistuneen pyynnön jälkeen päivitetään ostoskori.
				*/
				$(".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: