Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryManaging Website Forms

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Checkbox Shopping Cart

The shopper checks checkboxes. As that activity takes place, the total purchase price is updated.

When done selecting, the shopper taps a button to pay at PayPal.

The entire shopping cart is all on one page.

There is no provision to specify product quantity. This shopping cart is for products that typically are purchased individually — memberships, ebooks, courses, software, … .

Here is an example. (Note: Tapping the button will result in an error page at PayPal because the specified Merchant ID is fake.)

The Wonder Products!

Wonder Book
Wonder Course
Wonder Video
Total: $

Make a list of products and give each a checkbox. Images are optional.

The product checkbox has an id value that the JavaScript uses to calculate the total. The checkbox value contains the amount for the product it represents. And the checkbox name contains a name for the product.

The cart is submitted to a PHP script that logs the submission and sends the buyer to PayPal to arrange payment.

The Code Examples Cart — The following form is used in code examples in the rest of this document.

For contrast with the above illustrated cart, here is a checkbox shopping cart without illustrations. This design might fit better in your web page navigation or widget area.

Total: $

Tapping the button will result in an error page at PayPal because the specified Merchant ID in this example is fake.

If you wish to have the source code handy for the code examples cart, you can get it here (opens pre tag for code copying).

Implementing Checkbox Shopping Cart

Implementation is in three parts.

  1. The visible checkbox shopping cart: The cart has one or more products that can be chosen by checking its associated checkbox. It also has a place where the current total is published. And a link to pay.

  2. The JavaScript to add cart total: The JavaScript calculates and publishes the total of all product checkboxes that are checked. (Buyers who use browsers with JavaScript turned off can still submit their order. They just won't see the order total amount being updated as they choose what to buy.)

Both of the above are on the same web page. The next implementation part is a separate PHP script.

  1. The PHP script for the cart to submit to: This script logs the cart details and then sends the buyer to PayPal for arranging payment.

Those are the three parts. Each part is addressed separately.

The Visible Checkbox Shopping Cart

The shopping cart that people see has three elements. They are the products with checkboxes, the current-total amount, and the submit button.

All three elements are part of an HTML form.

Products With Checkboxes

The product name and image and whatever information you want with the product can be coded with your preferred style and design. A checkbox for choosing the product needs to be associated with the product.

The checkbox code is formatted in a special way. Here is a template.

<input 
   type="checkbox" 
   onclick="AddCheckedProducts()" 
   id="ID_VALUE" 
   name="PRODUCT_NAME" 
   value="PURCHASE_AMOUNT">

The JavaScript (further below) requires the onclick="AddCheckedProducts()" attribute be in each product checkbox field. It causes the current-total amount to be updated when the checkbox is checked or unchecked.

The three values colored blue need to be replaced with real data.

  1. Replace ID_VALUE with an id value that is unique on the web page.

  2. Replace PRODUCT_NAME with a version of the product name that makes a valid input tag name. It must begin with a letter and be composed of letters, numbers, and/or underscore characters.

    As an example, a product named "Orange Blossom Special" might be coded as an orange_blossom_special product name or perhaps OrangeBlossomSpecial.

    The name value in the checkbox input tag will be used as the product name for the PayPal payment. In other words, it should be recognizable for the buyer.

    Important: Do not use "x" or "y" as the product name. And don't name a product with a name that ends with "_x" or "_y". This is a special rule for this shopping cart. It will ignore fields with those names when it adds up the amount to pay at PayPal.

  3. Replace PURCHASE_AMOUNT with the purchase amount. Don't use any currency symbols. And no commas. But a period may be used when that is part of the amount being paid.

    Here are the checkbox fields from the code examples cart.

    <input
       type="checkbox"
       onclick="AddCheckedProducts()"
       id="wonder-book"
       name="wonder_book"
       value="3.33">
    
    <input
       type="checkbox"
       onclick="AddCheckedProducts()"
       id="wonder-course"
       name="wonder_course"
       value="300">
    
    <input
       type="checkbox"
       onclick="AddCheckedProducts()"
       id="wonder-video"
       name="wonder_video"
       value="30.95">
    

Follow the above method for each checkbox that is associated with a product available with your checkbox shopping cart.

Current-Total Amount

The current-total amount is a span tag with a unique id value. The id value is used by the JavaScript as the place to publish the current-total amount.

(Where to publish the current-content total is not limited to a span tag. The tag may be a div tag, a table td tag, or other HTML tag that can contain content.)

Here is the span tag from the code examples cart.

<span id="current-total-amount"></span>

And this is the code that publishes the entire line of the code examples cart that includes the current-total amount.

<p style="margin-top:.25em; margin-bottom:.25em;">
Total: $<span id="current-total-amount"></span>
</p>

Submit Button

The submit button is used to submit the form. It has no coding unique to the checkbox shopping cart.

Here is the code for a submit button.

<input
   type="submit"
   value="Pay at PayPal">

The button may be type="submit" or type="image". The code examples cart uses an image and here is the code that implements it.

<input
   type="image"
   src="https://www.willmaster.com/possibilities/images/20200421-issue-payatpaypal.png">

Either type="submit" or type="image" will submit the form.

The JavaScript to Add Cart Total

Below is the JavaScript that adds the checked products and publishes the total amount. Comments follow.

<script type="text/javascript">
/*
Checkbox Shopping Cart
Version 1.0
April 18, 2020
Will Bontrager Software LLC
https://www.willmaster.com/
*/

/* Customization (two places) */
// Place 1:
// Specify the id value where to publish the total 
//    amount of the order.

var CSC_total_spot2 = "current-total-amount";

//Place 2:
// Specify the checkbox id values, quoted and comma 
//    separated, all one line, within the parenthesis.

var CSC_checkbox_IDs2 = new Array( "wonder-book", "wonder-course", "wonder-video" );

/* End of customization */

function AddCheckedProducts()
{
   var value = 0.0;
   for( var i=0; i<CSC_checkbox_IDs2.length; i++ )
   {
      var d = document.getElementById(CSC_checkbox_IDs2[i]);
      if( d.checked ) { value += parseFloat(d.value); }
   }
   document.getElementById(CSC_total_spot2).innerHTML = value.toFixed(2);
}
AddCheckedProducts();
</script>

Customizations.

The JavaScript has two places to customize.

  1. If the id value of the current-total amount span tag is not current-total-amount, then replace current-total-amount with the correct id value.

  2. Find these id values in the code.

    "wonder-book", "wonder-course", "wonder-video"
    

    Replace those id values with the id value of each checkbox field that represents a product. The id values are enclosed in quotation marks and comma separated — all on one line.

When the JavaScript has been customized, place it on the web page with the HTML code for the checkbox shopping cart.

Put the JavaScript somewhere below the HTML code for the cart. It may be immediately below or further down, even at the end of the page.

The web page with the cart has now been completed. What is left is to install the PHP script to handle the checkbox shopping cart submission when someone wants to buy.

The PHP Script for the Cart To Submit To

The PHP script has four places to customize. Comments follow the source code.

<?php
/*
    Checkbox Shopping Cart Submission Handler
    Version 1.0
    April 18, 2020
    Will Bontrager Software LLC
    https://www.willmaster.com/
*/

/* Customizations */

// Specify where the relay-to-PayPal log 
//    should be at, relative to document 
//    root (formatted CSV).
$LogFileLocation = "/log/PayPalOrders.csv";

// Specify your PayPal email address or 
//    PayPal merchant account ID.
$BusinessID = "ABC123456789Z";

// Specify the URL the buyer's browser 
//    shall go to after payment is arranged.
$AfterPaymentURL = "https://example.com/paid.php";

// Specify the currency you want to be paid in.
$CurrencyCode = "USD";

/* End of customization. */

mb_regex_encoding('UTF-8');
mb_internal_encoding('UTF-8');
date_default_timezone_set('UTC');
$i = 0;
$Total = 0.0;
$Names = $Numbers = array();
foreach( $_POST as $k => $v )
{
   if( preg_match('/_(x|y)$/',$k) or preg_match('/^(x|y)$/',$k) ) { continue; }
   if( ! preg_match('/^[\$\d\.\,]+$/',$v) ) { continue; }
   $v = floatval(preg_replace('/[^\d\.]$/','',$v));
   if( $v < 0.01 ) { continue; }
   $i++;
   $Total += $v;
   $Names[] = $v;
   $Numbers[] = $i;
}
if( $Total > 0.01 )
{
   $LogLine = array();
   $LogLine[] = str_replace('"','""',date('r'));
   $LogLine[] = $_SERVER['REMOTE_ADDR'];
   $LogLine[] = $Total;
   $LogLine[] = str_replace('"','""',implode(',',$Names));
   $LogLine[] = str_replace('"','""',$_SERVER['HTTP_USER_AGENT']);
   file_put_contents($_SERVER['DOCUMENT_ROOT'].$LogFileLocation,'"'.implode('","',$LogLine)."\"\n",FILE_APPEND);
   $items = array();
   $items[] = "amount=$Total";
   $items[] = 'item_name='.rawurlencode(implode(',',$Names));
   $items[] = 'item_number='.rawurlencode(implode(':',$Numbers));
   $items[] = 'return='.rawurlencode($AfterPaymentURL);
   $items[] = 'business='.rawurlencode($BusinessID);
   $items[] = "currency_code=$CurrencyCode";
   $items[] = 'charset=UTF-8';
   $items[] = 'no_shipping=1';
   $PayPalURL = 'https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&'.implode('&',$items);
   header("Location: $PayPalURL");
   exit;
}
echo '<p>Something went awry. Perhaps no products were checked for purchase.</p>';
exit;
?>

Customizations.

The PHP script has four places to customize.

  1. Replace /log/PayPalOrders.csv with the file location for the PayPal order data CSV file. The location needs to be specified as relative to document root, which is the directory where your domain's home or index file is located.

    The PayPal order data file is a CSV file that contains the date/time, the buyer's IP address, the total amount, the amount of each product being ordered, and the browser's user agent string.

  2. Replace ABC123456789Z with either your PayPal Merchant ID or your PayPal email address.

  3. Replace https://example.com/paid.php with the URL where you want the buyer's browser to go to after payment has been arranged at PayPal. This would generally be a thank-you page.

  4. Replace USD with the currency code you want to be paid in. USD is the code for US Dollar. If you don't know what the currency code is for your preferred currency, an internet search for "currency codes" can lead to official lists of currency codes. PayPal is also likely to have a list on their site somewhere.

When the customizations are done, save the PHP script as CheckboxShoppingCart.php or other .php file name you prefer.

Upload CheckboxShoppingCart.php to your server into a directory accessible with browsers. Make a note of its URL.

In the form tag of the HTML part of the checkbox shopping cart, replace the current value of the action attribute with the URL of the newly installed CheckboxShoppingCart.php script.

Checkbox Shopping Cart has now been installed and is ready for testing.

(This article first appeared with an issue of the Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC