Passing Data Between Pages: Ionic 2

Today lets see how we can pass data between pages in ‘Ionic 2’ application.

Related Read:
Basic Navigation: Ionic 2
Details Arrow: Ionic 2
Basics of Injectable or Providers: Ionic 2

ionic2-passing-data-between-pages

Passing Data Between Pages: Ionic 2


[youtube https://www.youtube.com/watch?v=0JtS8fHR1Co]

YouTube Link: https://www.youtube.com/watch?v=0JtS8fHR1Co [Watch the Video In Full Screen.]



src/providers/data.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
 
@Injectable()
export class Data {
data: any;
  constructor(public http: Http) {
    this.data = [
      {name: 'Microsoft', code: 324, product: 'Windows 10'},
      {name: 'Apple', code: 678, product: 'iPhone 7'},
      {name: 'Google', code: 567, product: 'Pixel'},
      {name: 'Oracle', code: 89, product: 'RDBMS'},
      {name: 'IBM', code: 542, product: 'Computer Hardware and Software'}
    ];
  }
 
  loadAll(){
      return Promise.resolve(this.data);
  };
  getByID(id){
    for(var i=0; i< (this.data).length; i++)
    {
      if(this.data[i].code == id)
      {
        return Promise.resolve(this.data[i]);
      }
    }
  };
}

Here we have an array variable(data) which has couple of objects which has company name, product name and an unique code associated with each object. We also have loadAll() method which simply returns this data array variable as promise.

We also have another method called getByDI() which receives an argument. Inside this method, we loop thought the array variable(data) and return the matching id’s object as promise.

src/pages/home/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Data } from '../../providers/data';
import { SecondPage } from '../second/second';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  companies: any = 0;
  constructor(public navCtrl: NavController, public data: Data) {
        this.data.loadAll().then(result => {
            this.companies =  result;
        });
  }
  detailsPage(id){
    this.navCtrl.push(SecondPage, {code: id});
  };
}

Here we invoke loadAll() method and assign the returned result to companies variable. We also have detailsPage() method which pushes the SecondPage reference to navigation stack and also assigns the value of id to a property called code(we can name this property anything we want). Also note that we have assigned the initial value of companies variable to zero.

src/pages/home/home.html

  < ion-spinner name="circles" *ngIf="companies == 0">
  < /ion-spinner>
  < ion-list *ngIf="companies != 0" no-lines>
    < ion-item *ngFor="let Company of companies" 
              (click)="detailsPage(Company.code);" detail-push>
      {{Company.name}}
    < /ion-item>
  < /ion-list>

Here we show a spinner component until the promise gets resolved. Once the variable companies has some other value than zero, the list items gets displayed. When the user clicks on any of the list item, we invoke detailsPage() method and also pass in its corresponding unique code to the method.

Generating page using Ionic 2 CLI

ionic g page pageName

src/pages/second/second.ts

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Data } from '../../providers/data';
 
@Component({
  selector: 'page-second',
  templateUrl: 'second.html'
})
export class SecondPage {
  company: any = 0;
  constructor(public navCtrl: NavController, 
              public navParams: NavParams, 
              public data: Data) {
    this.data.getByID(this.navParams.get('code')).then(result => {
      this.company = result;
    });
  }
}

Here we import NavParams class and using the NavParams reference object and its get method we retrieve the value passed in by the home page to second page. We pass this value to getByID() method and receive details of company which has this unique code as id. Also note that we have assigned zero as initial value to the variable company.

src/pages/second/second.html

< ion-spinner name="circles" *ngIf="company == 0">
< /ion-spinner>
< ion-content padding *ngIf="company != 0">
< h2>{{company.name}}< /h2>
< strong>Product: < /strong> {{company.product}}
< /ion-content>

Here we show a spinner component until the promise resolves and the company variable have required results in it.

Important:
1. Make sure to initialize the variables(companies and company variable in our example) and show a spinner or do something with the initial value before trying to access the properties the actual results has – because, if you try to access properties of the result before the promise has resolved, you’ll get errors.
For example: In our example, we have name and product properties. If I try to access company.name and company.product before the promise has resolved we’ll get the error – that the name and property of undefined CAN NOT be accessed.

2. Make sure to import all the pages and providers(in our case pages like homepage, second page and Data provider) inside src/app/app.module.ts file and specify the class names and data provider name in appropriate places/blocks/sections as shown in the video tutorial.

Basic Navigation: Ionic 2

Today lets learn basics of navigation / routing in Ionic 2. Ionic 2 and Angular 2 makes use of navigation stack for its navigation system. i.e., we can push and pop views to and from navigation stack.

Forward Navigation: We push page reference of the page we want to navigate to.
Backward Navigation: We execute pop operation on navigation stack to remove the current view or top view.

Once we push a page reference of the page we want to navigate to, a back button or back arrow symbol is automatically added to the navigation bar and whenever user clicks on it, the pop operation is executed for us automatically.

Basic Navigation or Routing: Ionic 2


[youtube https://www.youtube.com/watch?v=VC-drnHG8Gg]

YouTube Link: https://www.youtube.com/watch?v=VC-drnHG8Gg [Watch the Video In Full Screen.]



Generating Page using Ionic 2 CLI(Command Line Interface)

ionic g page Second

OR

ionic generate page Second

This command creates Second page for us – which will have a TypeScript page(class file or component), a template file and a sass file.

src/pages/home/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { SecondPage } from '../second/second';
 
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public navCtrl: NavController) {}
  nextPage(){
    this.navCtrl.push(SecondPage);
  }
}

Here we import the SecondPage page. Next define nextPage method. When nextPage method is invoked, we push reference to the page we want to navigate to, to the NavController reference.

Important: Also make sure to import Second page inside src/app/app.module.ts file and specify the page reference inside declarations and entryComponents section.

src/pages/home/home.html

 < button ion-button (click)="nextPage();">
   Next Page
 < /button>

Here we invoke nextPage method when user clicks on ‘Next Page’ button. This should take the user to the second page. And the user will be presented with a back button in the second page, so that he or she can navigate back to the home page or the first page again – which calls pop method on NavController reference automatically.

Set Root Page

this.navCtrl.setRoot(SecondPage);

using setRoot method, and passing the page reference of the page you want to set as root page, you can set the root page dynamically.

src/pages/second/second.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
 
@Component({
  selector: 'page-second',
  templateUrl: 'second.html'
})
export class SecondPage {
  constructor(public navCtrl: NavController) {
    this.navCtrl.setRoot(SecondPage);
  }
}

Next Video Tutorial
In the next video tutorial we shall learn to pass data between pages while navigating.

Simple / Basic Pagination / Navigation: PHP & MySQL

The Best and The most Simple Pagination / Navigation using PHP and MySQL

To know more about our simple Create, read, update and delete application, follow these short videos and notes:
First look at these short videos:
Connect to the database
Simple / basic insertion operation
Insertion of Records into Database using Forms: PHP & MySQL (important)
SELECT / LIST Records From Database Table: PHP & MySQL
UPDATE / EDIT Records In Database Table: PHP & MySQL
Delete / Remove Records In Database Table: PHP & MySQL

These are the entries in our table apple:
1Google USA
2Apple USA
3Microsoft USA
4Oracle USA
10IBM
11HP
12Symantec
13Adobe
14Cisco
15McAfee
16Red Hat
17Sun Microsystems
18Intel
19Salesforce
20Facebook
21Technotip
22MindTree
23Tate Consultancy Ser
24Cognizant
25Citigroup
26Maestro
27Visa
28KingFisher
29HDFC
30ICICI
31SBI
32SBM
33Twitter
34LinkedIn
35BlueDart
36VRL
37Zappos
38FlipKart
39Amazon
40Yahoo!
41ebay
42PayPal

We would split these entries into 5 segments each and display 5 records at a time.

In this video tutorial we’re showing the latest entry first. If you want to show first entry first, then take another database field called date and insert the date and time of the insertion operation. Now using the WHERE clause and LIMIT fetch the data from database and display as you wish.

WHERE clause and LIMIT, to fetch depending on date and time
mysql query

1
mysql> SELECT * from apple [ WHERE some_condition ] ORDER BY date ASC LIMIT $start, 5;
1
mysql> SELECT * from apple [ WHERE some_condition ] ORDER BY date DESC LIMIT $start, 5;

In our tutorial, we have taken id as primary key and as AUTO_INCREMENT field.

1
2
3
4
5
6
7
8
9
10
11
$rs = mysql_query("SELECT count(*) FROM apple");
$rw = mysql_fetch_array($rs);
 
if( !(isset($_GET['page'])) )
    $start = $rw[0] - 5;
else
    $start = $rw[0] - ($_GET['page'] * 5);
 
 
$res = mysql_query("SELECT * FROM apple LIMIT $start, 5") 
                              or Die("More entries coming, stay tuned!");

First we need to calculate the number of records present inside the table. Next decide onto how many items you want to display.
Based on this, subtract the actual number of records with number of items you actually want to display.

If use explicitly passes $_GET[‘page’] i.e., by clicking on the navigation or pagination numbers, then multiply the number with the number of items you want to display and subtract it with the actual number of records present inside the table.

The final step is to, pass the $start and the number till which you want to fetch from $start.

In our case, we want to show 5 items from the table apple, so we give the limit: starting from $start to 5 records after $start.

Video Tutorial: Simple / Basic Pagination / Navigation: PHP & MySQL


[youtube https://www.youtube.com/watch?v=06o4C32B6Bg]

YouTube Link: https://www.youtube.com/watch?v=06o4C32B6Bg [Watch the Video In Full Screen.]



Complete Code
index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
< ?php
include_once('db.php');
 
if(isset($_POST['name']))
{
  $name = $_POST['name'];
 
  if(mysql_query("INSERT INTO apple VALUES('','$name')"))
echo "Successful Insertion!";
  else
echo "Please try again";
}
 
 
$rs = mysql_query("SELECT count(*) FROM apple");
$rw = mysql_fetch_array($rs);
 
if( !(isset($_GET['page'])) )
    $start = $rw[0] - 5;
else
    $start = $rw[0] - ($_GET['page'] * 5);
 
 
$res = mysql_query("SELECT * FROM apple LIMIT $start, 5") 
                                  or Die("More entries coming, stay tuned!");
 
 
?>
<html>
<head>
 
<style type="text/css">
 li { list-style-type: none; display: inline; padding: 10px; text-align: center;}
// li:hover { background-color: yellow; }
</style>
 
</head>
<body>
<form action="." method="POST">
Name: <input type="text" name="name"/><br />
<input type="submit" value=" Enter "/>
</form>
 
<h1>List of companies ..</h1>
<ul>
< ?php
while( $row = mysql_fetch_array($res) )
  echo "<li>$row[name] 
                <li><a href='edit.php?edit=$row[id]'>edit</a></li>
                <li><a href='delete.php?del=$row[id]'>delete</a></li><br />";
 
?>
</ul>
<ul>
<li><a href="index.php?page=1">1</a></li>
<li><a href="index.php?page=2">2</a></li>
<li><a href="index.php?page=3">3</a></li>
<li><a href="index.php?page=<?php 
  if(isset($_GET['page'])) 
     $next = $_GET['page'] +1; 
  else 
     $next=2; 
  echo $next; ?>">next</a>
</li>
</ul>
</body>
</html>

Error:
Notice: Undefined index: page

Make sure you have written proper code near next link in the navigation / pagination numbering..

1
2
3
4
5
6
7
8
9
10
<li>
<a href="index.php?page=<?php 
  if(isset($_GET['page'])) 
     $next = $_GET['page'] +1; 
  else 
     $next=2; 
 
  echo $next; 
?>">next</a>
</li>

First we check if $_GET[‘page’] is set. If not set, then we give a value of 2 to next orelse we assign the next value to $_GET[‘page’].

Also check:
GET method in action
POST method in action