How to build HTML5 Shopping Cart app using Ionic Cordova : Part 4

This article will discuss on, how to  Implement a shopping cart app using html5 cordova.Here i will give you the basic overview on, how i implemented  product listing in my FoodKart App. Later in the Part 5 of this series, i will show, how the entire application was implemented.

If you find it difficult to follow, please go through my previous articles:

Ionic HTML5 Basic concepts

How to design HTML5 app using Ionic Cordova : Part 2

How to build HTLM5 app using Ionic Cordova: Part 3

UPDATE (10-07-16):

Latest FoodKart V0.3 is released. Read the complete tutorial here.

fk-latest

NUTSHELL :-

  1. Variable names in java script can be used in HTML as {{ variable_name }}
  2. Populating a List is done is using ng-repeat
  3. ActionListener for HTML entities using ng-click
  4. Controllers is the place where you write action events.

[wpi_designer_button text=’Download’ link=’https://github.com/arjunsk/FoodKart’ style_id=’48’ icon=’github’ target=’_blank’]

LEVEL 1  [ Basic] :-

  1. The main part of building the Ionic Cordova App comes in modifying, the files in WWW directory.
    www directory files

2.

  • JS contains the  Java script files i.e. the file responsible for actions.
  • Templates contains the html5 pages i.e. different screens of your App.
  • index.html :  is the main container used to display your pages.It will also contain elements that are shared throughout the app.
    For eg :- Navigation Bar, js files etc.
  • img is the place where you put the images associated with the app.
  • css is the place where you put the custom style files for your app.
  • lib is the place containing ionic library files.

3. We call the js variable in HTML using  {{ variable_name }}

4. To populate an list ionic :

<ion-list ng-repeat="item in menu_items">   // ng-repeat is similar to for-each loop
	<ion-item>
		<h2> {{ item.property_name }} </h2>
	</ion-item>    
</ion-list>

//menu_items is array of items (objects) declared in the respective controller.

5. To call an action listener in Ionic:  [ applicable to all HTML entity ]

<a ng-click="function_name(parameter1,parameter2 ....  )" > </a>

// ng-click is applicable on any clickable html entity

 

LEVEL 2  [ Intermediate: will be focusing on offline concepts ] :-

  1. Adding icon for Cart, Profile, Home in Navigation Bar.  [ shown as Section 1 in the image below ]

You can find the reference samples: http://ionicframework.com/docs/components/

1

[color-box]  index.html [The container]  [/color-box]

 <body ng-app="app" animation="slide-left-right-ios7"> // The body tag
  <div>
    <div>
        <ion-nav-bar class="bar-positive" >     // The navigation bar container 
	
            <ion-nav-back-button   side="left" class="button-icon icon ion-arrow-left-c">  //Back arrow icon
			</ion-nav-back-button>
		
			<ion-nav-buttons side="right"   >    // "right" aligned			
				<div ng-controller="indexCtrl">   // "indexCtrl" (\www\js\controllers.js) contains the action calls  
				   
				    //icons for home , profile and cart
					<a href="#/page1" class="button  button-icon ion-android-home"></a>    
					<a href="#/page4" class="button  button-icon ion-android-person"></a>
					<a  href="#/page2" class="button  button-icon ion-android-cart" ></a>
					
				</div>
			</ion-nav-buttons>
				
        </ion-nav-bar>

        <ion-nav-view></ion-nav-view>   // container that shows the html pages in template folder [Reference 1]
    </div>
  </div>
</body>

 

2. Creating the menu page. [ Section 2 in the image ]

We have already created a basic list layout from How to design HTML5 app using Ionic Cordova : Part 2

We just need to add cart icon on every list item, and some basic formatting

[color-box]  templates\menu.html [Menu page i.e. Main page]  [/color-box]

<ion-view title="Menu">  // [Reference 1]
	
	// avoid padding to get the native feel.
	// Header section is used to show title for the page ie Menu, Product, Cart etc
    <ion-content padding="'false'" class="has-header">  
	
		// Search bar
        <form class="list">
            <label class="item item-input">
                <i class="icon ion-search placeholder-icon"></i>
                <input type="search" placeholder="">
            </label>
        </form>
    
	 //Sort bars
      <div class="button-bar">
            <a href="#/page6" class="button button-stable button-block  icon-left ion-android-funnel">Filter</a>
            <a href="#/page7" class="button button-stable button-block  icon ion-android-restaurant">Sort</a>
        </div>
	
	// List	
        <ion-list ng-repeat="item in menu_items">  // ng-repeat is a loop ie  for-each(item in menu_items)
        

			// individual list item
			<ion-item class="item-thumbnail-left" >  // sets thumbnail to left
			
				  // <img> is used to show product image
			     // ng-src is similar to src in html. It is used to give the image location
				 // ng-click is similar to  onClickListener() . Here it trigers showProductInfo() function passing the respective item parameters.
                <img  ng-src="{{'img/'+ item.p_image_id +'.jpg'}}"  ng-click="showProductInfo(item.p_id,item.p_description,item.p_image_id,item.p_name,item.p_price)" >
				
				//used <p> to position cart icon to right 
				// Calling addToCart() function with parameters passed
				<p style="position:absolute;right:10px;">
				<a  ng-click="addToCart(item.p_id,item.p_image_id,item.p_name,item.p_price)" class="button  button-balanced button-clear   icon ion-android-cart">  </a> 
				</p>
                
				//product name displayed using heading tag ie <h2>
				//Calling showProductInfo() function with parameters passed
				<h2  ng-click="showProductInfo(item.p_id,item.p_description,item.p_image_id,item.p_name,item.p_price)" > {{item.p_name}} </h2>
                
				//<p> is used to show product price
				//Calling showProductInfo() function with parameters passed
				<p   ng-click="showProductInfo(item.p_id,item.p_description,item.p_image_id,item.p_name,item.p_price)">Price: ${{item.p_price}}</p>
			
			</ion-item>
			 
        </ion-list>
    </ion-content>
</ion-view>

 

3. To implement listing of items from the server, we are basically parsing JSON response.

[color-box]  js\controllers.js [ ActionListener  ]  [/color-box]

.controller('menuCtrl', function($scope,$http) {
				
	//$scope.$on----> onload event
	$scope.$on('$stateChangeSuccess', function () {
		
		str="http://www.yoursite.com/foodkart-server-files/food_menu.php";
		
		$http.get(str).    // sends request for the file
		success(           // if seccusfull response is recieved
			function (response){  // if response is not null 
				$scope.menu_items = response.records;   // set menu_items array with items from response
			}
		);	
			
	}); // end of '$scope.$on'
}

[color-box]

Note:

$scope.$on(‘$stateChangeSuccess’, function () { . . . } is used to detect if the page url has changed.

It can also be used to detect if the controller page is active or not.

[/color-box]

 

4. Now you might be thinking “How menuCtrl is linked with the menu page? ”

It is linked in the following file www\js\routes.js

    .state('menu', {
      url: '/page1',
      templateUrl: 'templates/menu.html',
      controller: 'menuCtrl'
    })

 

5. In the server side we use PHP to output JSON response for listing the products.

<?php

// Used to output JSON data
header("Access-Control-Allow-Origin: *");   
header("Content-Type: application/json; charset=UTF-8");

//used to establish connection
$conn = new mysqli("localhost", "mysql username", "mysql password", "mysql database");

// query to retrieve the products
$query="SELECT p_id,p_name,p_description,p_image_id,p_price FROM products where p_available=1 ";

//generates the result
$result = $conn->query($query);
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != "") {$outp .= ",";}
    $outp .= '{"p_id":"'  . $rs["p_id"] . '",';
    $outp .= '"p_name":"'   . $rs["p_name"]        . '",';
	$outp .= '"p_description":"'   . $rs["p_description"]        . '",';
	$outp .= '"p_image_id":"'   . $rs["p_image_id"]        . '",';
	$outp .= '"p_price":"'. $rs["p_price"]     . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();

//outputs the content
echo($outp);
?>

 

6. This is the MYSQL Table for Products

--
-- Table structure for table `products`
--

CREATE TABLE IF NOT EXISTS `products` (
  `p_id` varchar(5) NOT NULL,
  `p_name` varchar(30) NOT NULL,
  `p_description` varchar(300) NOT NULL,
  `p_category` varchar(30) NOT NULL,
  `p_image_id` varchar(500) NOT NULL,
  `p_price` int(11) NOT NULL,
  `p_available` tinyint(1) NOT NULL,
  `p_stock` int(11) NOT NULL,
  PRIMARY KEY (`p_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`p_id`, `p_name`, `p_description`, `p_category`, `p_image_id`, `p_price`, `p_available`, `p_stock`) VALUES
('1', 'Paneer Masala', 'Paneer Masala Description', '1', 'cv1wVOtRnmMJtzNlo4Ew_2', 20, 1, 100),
('2', 'Tandoori Chicken', 'Tandoori Description', '2', 'CARLvOcNTQmqVv42rhFz_1', 30, 1, 100),
('3', 'Gopi Manchurian', 'Gopi Description', '1', 'JhMIxzQXmB03SXPg84Iw_3', 20, 1, 100),
('4', 'Grilled Chicken', 'Grilled Chicken Description', '2', 'd5R11v9fRuvAx8wKYIWP_4', 40, 1, 100),
('5', 'Chana Masala', 'Chana Masala Description', '1', 'JhMIxzQXmB03SXPg84Iw_3', 10, 1, 100);

-- --------------------------------------------------------

7. Sample JSON Response.

{
   "records":[
      {
         "p_id":"1",
         "p_name":"Paneer Masala",
         "p_description":"Paneer Masala Description",
         "p_image_id":"cv1wVOtRnmMJtzNlo4Ew_2",
         "p_price":"20"
      },
      {
         "p_id":"2",
         "p_name":"Tandoori Chicken",
         "p_description":"Tandoori Description",
         "p_image_id":"CARLvOcNTQmqVv42rhFz_1",
         "p_price":"30"
      },
      {
         "p_id":"3",
         "p_name":"Gopi Manchurian",
         "p_description":"Gopi Description",
         "p_image_id":"JhMIxzQXmB03SXPg84Iw_3",
         "p_price":"20"
      },
      {
         "p_id":"4",
         "p_name":"Grilled Chicken",
         "p_description":"Grilled Chicken Description",
         "p_image_id":"d5R11v9fRuvAx8wKYIWP_4",
         "p_price":"40"
      },
      {
         "p_id":"5",
         "p_name":"Chana Masala",
         "p_description":"Chana Masala Description",
         "p_image_id":"JhMIxzQXmB03SXPg84Iw_3",
         "p_price":"10"
      }
   ]
}

UPDATE: ( 31-07-2016)

Here is a video demo of setting up Ionic Cart!

 

 

Advertisement

6 thoughts on “How to build HTML5 Shopping Cart app using Ionic Cordova : Part 4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s