How to fetch and display remote data using login credentials in ionic app

Posted on Posted in Beginner

In this tutorial, we are going to fetch and display remote data using login credentials, this tutorial is a continuation of my earlier tutorial on How to setup login-register in ionic3 using PHP, MySQL, based on popular demand.

It is an application of two different tutorials I have covered in the past, namely How To Pass Data Between Pages In Ionic 2+ Application and How to write, read and display data from MySQL database in ionic app

Prerequisite

To follow this tutorial, you will need to first go through my earlier tutorial on How to setup login-register in ionic3 using PHP, MySQL. Because that is where it all started and some of the files we are going to be using here are from the said tutorial.

To accomplish our task of day, we need to do the following

  1. Modify home.ts file to pass data to another page after successful login
  2. Create a new page called profile page
  3. Create a php file to fetch information from the our MySQL server
  4. Create a method to display retrieved information
  5. Update profile html file to display retrieved information
  6. Test our application.

Are……you……ready???

  1. Modify home.ts file to pass data to another page after successful login

Add the following code to the conditional statement after successful login

this.navctrl.push(ProfilePage, data);

ProfilePage is underlined? Don’t worry, it’s because we have not created Profile Page which we are going to do in the next section.



  1. Create a new page called profile page

Now, let’s create profile page, from CLI as shown below

creat a new page

Now, open app.modules.ts under src/app/  and do the following

  1. Import ProfilePage from its location
  2. Add ProfilePage to declaration and entryComponents section

 

Your app.module.ts will look like this:( see How To Navigate Between Pages In Ionic 2+ Application

For details)

app.module.ts

 


  1. Create a php file to fetch information from the our MySQL server

Let’s head to our favourite text editor, open a new file and copy the following code into it

<?php

if (isset($_SERVER['HTTP_ORIGIN'])) {

        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");

        header('Access-Control-Allow-Credentials: true');

        header('Access-Control-Max-Age: 86400');    // cache for 1 day

    }

 

    // Access-Control headers are received during OPTIONS requests

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

 

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))

            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");        

 

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))

            header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

 

        exit(0);

    }

               

require "config.php";

  $data = file_get_contents("php://input");

    if (isset($data)) {

        $request = json_decode($data);

        $username = $request->username;

               }

 

$sql ="SELECT * FROM users WHERE username='$username'  ;";

 $result = mysqli_query($con, $sql);

 $response = array();

 while($row = mysqli_fetch_array($result))

{

                array_push($response, array("id"=>$row[0],

                                                                "username"=>$row[1],

                                                                "password"=>$row[2],

                                                                 "telephone"=>$row[3],

                                                                  "email"=>$row[4] ));

}

 echo json_encode(array("server_response"=> $response));

mysqli_close($db)

 ?>

Save the file as retrieve_data.php




  1. Create a method to display retrieved information

Open profile.ts file and modify it as shown below

import { Component } from '@angular/core';

import { IonicPage, NavController, NavParams } from 'ionic-angular';

import {Http, Headers, RequestOptions}  from "@angular/http";

import { LoadingController } from 'ionic-angular';

import 'rxjs/add/operator/map';

/**

 * Generated class for the ProfilePage page.

 *

 * See https://ionicframework.com/docs/components/#navigation for more info on

 * Ionic pages and navigation.

 */

@IonicPage()

@Component({

  selector: 'page-profile',

  templateUrl: 'profile.html',

})

export class ProfilePage {

data:any;

username:any;

items:any;

  constructor(public navCtrl: NavController, public navParams: NavParams,  private http: Http,  public loading: LoadingController) {

  }

  ionViewDidLoad() {

    console.log('ionViewDidLoad ProfilePage');

  }

  ngOnInit(){

    this.username = this.navParams.get('username');

   

var headers = new Headers();

headers.append("Accept", 'application/json');

headers.append('Content-Type', 'application/json' );

let options = new RequestOptions({ headers: headers });

let data = {

    username: this.username

     };

let loader = this.loading.create({

content: 'Processing please wait...',

});

loader.present().then(() => {

this.http.post('http://ionicdon.com/mobile/fetch_data2.php',data, options)

.map(res => res.json())

    .subscribe(res => {

     loader.dismiss()

    this.items=res.server_response;

    console.log(this.items);

    });

    });

     }

    }

 

  1. Update profile html file to display retrieved information

To update profile.html file to display retrieved information, copy the following code between <ion-content> </ion-content> tag as follows

<ion-content padding>

<ion-item *ngFor="let item of items" >

  <h2>Welcome {{item.username}}</h2>

  <h3>Your profile information is as follows:</h3>

  <ion-row>

    <ion-col col-4>

     Password

    </ion-col>

    <ion-col col-8>

  {{item.password}}

    </ion-col>

</ion-row>

<ion-row>

    <ion-col col-4>

      Telephone

    </ion-col>

    <ion-col col-8>

  {{item.telephone}}

    </ion-col>

</ion-row>

<ion-row>

    <ion-col col-4>

    Email

    </ion-col>

    <ion-col col-8>

  {{item.email}}

    </ion-col>

</ion-row>

 </ion-item>

</ion-content>




  1. Test our application.

Congratulations, we are through I salute you for your tenacity, well done, now let us test our application. Go to command prompt, change directory to your app folder and type

ionic serve –l

 

Do you have what I have below after login?

application output after login




14 thoughts on “How to fetch and display remote data using login credentials in ionic app

  1. I am facing a challenge. An error with property ‘username’ of undefined, also, ERROR SyntaxError: Unexpected token {

    //this.http.post(‘http://localhost:90/totallight/api/login.php’,data,options)

    this.http.post(‘http://edomonitor.com/school-evaluation-api/login.php’,data,options)

    .map(res => res.json())

    .subscribe(res => {

    //this.data = data[“_body”];

    console.log(data)

    loader.dismiss()

    if(res == “Your Login success”){
    // let username = this.data;

    this.navCtrl.push(UserPage, data);

    /*this.navCtrl.push(UserPage, {

    userData: this.username.value

    });*/

    }

    else

    {

    let alert = this.alertCtrl.create({

    title:”ERROR”,

    subTitle:”Invalid username/password”,

    buttons: [‘OK’]

    });

    alert.present();

    }

    });

    });

    }

    }

    }

    user.ts

    import { Component } from ‘@angular/core’;
    import { IonicPage, NavController, NavParams } from ‘ionic-angular’;
    import {Http, Headers, RequestOptions} from “@angular/http”;
    import { LoginPage } from ‘../login/login’;
    import { PostPage } from ‘../post/post’;
    import { LoadingController } from ‘ionic-angular’;
    //import {Http} from “@angular/http”;
    import ‘rxjs/add/operator/map’;
    import {FormGroup, FormControl } from ‘@angular/forms’;

    /**
    * Generated class for the UserPage page.
    *
    * See https://ionicframework.com/docs/components/#navigation for more info on
    * Ionic pages and navigation.
    */

    @IonicPage()
    @Component({
    selector: ‘page-user’,
    templateUrl: ‘user.html’,
    })
    export class UserPage {

    data:any;
    username:any;
    items:any;

    userData : any;
    langs;
    langForm;

    constructor(public navCtrl: NavController, public loading: LoadingController, private http: Http, public navParams: NavParams) {
    this.userData= navParams.data.userData;

    this.langForm = new FormGroup({
    “langs”: new FormControl({value: ‘Co-educational school’, disabled: false})
    });

    }

    ionViewDidLoad() {
    console.log(‘ionViewDidLoad UserPage’);
    }

    logout(){
    this.navCtrl.push(LoginPage);
    }

    survey(){
    this.navCtrl.push(PostPage, {
    //userData: this.userData
    });

    }

    ngOnInit(){

    this.username = this.navParams.get(‘username’);

    var headers = new Headers();

    headers.append(“Accept”, ‘application/json’);

    headers.append(‘Content-Type’, ‘application/json’ );

    let options = new RequestOptions({ headers: headers });

    let data = {

    username: this.username

    };

    let loader = this.loading.create({

    content: ‘Processing, please wait…’,

    });

    loader.present().then(() => {

    this.http.post(‘http://edomonitor.com/school-evaluation-api/retrieve_data.php’,data, options)

    .map(res => res.json())

    .subscribe(res => {

    loader.dismiss()

    this.items=res.server_response;

    console.log(this.items);

    });

    });

    }

    }

  2. Great put up, very informative. I wonder why the opposite experts of this sector do not realize this. You must proceed your writing. I’m sure, you have a great readers’ base already!|What’s Taking place i’m new to this, I stumbled upon this I’ve discovered It positively helpful and it has aided me out loads. I hope to give a contribution & aid different customers like its aided me. Good job.

  3. Hi
    before $data = file_get_contents(“php://input”);
    there is a require calling config.php, but this file is missing in your article.
    Is for the connection to the db right?
    Thanks for your work.

  4. Hello there, just became aware of your blog through
    Google, and found that it is really informative.
    I’m gonna watch out for brussels. I will appreciate if you
    continue this in future. Many people will be benefited from your writing.
    Cheers!

  5. Hey there would you mind stating which blog platform you’re working with?
    I’m looking to start my own blog soon but I’m having a tough time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems different then most blogs and I’m looking for something unique.
    P.S My apologies for getting off-topic but I had to ask!

  6. Hi. I see that you don’t update your blog too often. I know that writing content is boring and time consuming.

    But did you know that there is a tool that allows you to create new posts using existing content (from article directories or other pages from
    your niche)? And it does it very well. The new posts are
    unique and pass the copyscape test. Search in google and try:
    miftolo’s tools

    1. this is the config.php file

      < ?php define('HOST',' your_host_server'); define('USER','your_username'); define('PASS','your_password'); define('DB','your_database_name'); $con = mysqli_connect(HOST,USER,PASS,DB); if (!$con){ die("Error in connection" . mysqli_connect_error()) ; } ?>

Leave a Reply

Your email address will not be published. Required fields are marked *