Ionic - SearchBar with Mysql Script

Hello i made a ionic searchbar script returns the items[] ok but i want to connect it with my php authservice and return the results from a php function.

I already connected my app with the authservice and i have returned JSON data in other pages so the authservice works fine i just don’t know how to put the php function in here

this.items = [
{ title: ‘one’ },
{ title: ‘two’ },
{ title: ‘three’ },
{ title: ‘four’ },
{ title: ‘five’ },
{ title: ‘six’ }
];

this is what i’ve done so far.

searchPage.ts

@Component({ selector: “page-search”, templateUrl: “search.html” })
export class SearchPage {
items: any;
filtereditems: any;
searchTerm: string = ‘’;
public noRecords: boolean;

constructor(
public common: Common,
public navCtrl: NavController,
public app: App,
public menu: MenuController,
public authService: AuthService,
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen
) {
this.items = [
{ title: ‘one’ },
{ title: ‘two’ },
{ title: ‘three’ },
{ title: ‘four’ },
{ title: ‘five’ },
{ title: ‘six’ }
];
this.filtereditems = [];
}

filterItems() {
console.log(this.searchTerm);
this.filtereditems = this.items.filter((item) => {
return item.title.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1;
});
}

searchPage.html

{{item.title}}

Any hint?

Please provide clear explanation,so that we can help …!!
I’m unable to understand the problem.

By reading it again n again ,i hv deduced that instead of filtering the items in js, you want to filter it in the PHP backend , frankly speaking it’s not a feasible option for a mobile app.

OK i can do that. Fix the problem through the php function but where do i call the php function on the .ts file?

php function

 $request = \Slim\Slim::getInstance()->request();
 $data = json_decode($request->getBody());
$uid=$data->uid;
$searchword=$data->searchword;
try {
	$key=md5(SITE_KEY.$data->uid);
	if($key==$data->token)
	{
	$db = getDB();
	$sql = "(SELECT name as name,username as username,uid as id,bio as aboutme, 'user' as type, profile_pic as pic, 'U' as mediatype FROM users WHERE status='1' AND username LIKE :searchword OR status='1' AND name LIKE :searchword ORDER BY uid DESC)
	
	UNION
	(SELECT title as name,'' as username, msg_id as id,description as aboutme, 'media' as type, media_pic as pic, type as mediatype  FROM messages WHERE message LIKE :searchword OR title LIKE :searchword  ORDER BY msg_id DESC ) 

	UNION
	(SELECT group_name as name,'' as username, group_id as id, group_desc as aboutme, 'group' as type, group_pic as pic, 'G' as mediatype FROM groups WHERE group_name LIKE :searchword or group_desc LIKE :searchword ORDER BY group_id ) LIMIT 8";
	$stmt = $db->prepare($sql);
	$q = "%".$searchword."%";
	$stmt->bindParam("searchword", $q,PDO::PARAM_STR);
	$stmt->execute();
	$userGroupSearchCount=$stmt->rowCount();
	$userGroupSearch = $stmt->fetchAll(PDO::FETCH_OBJ);
	if($userGroupSearch)
	{
   
    for($z=0;$z<$userGroupSearchCount;$z++)
    {
      if($userGroupSearch[$z]->name)
      {
      	//$userGroupSearch[$z]->name=nameFilter(htmlCode($userGroupSearch[$z]->name),16);
      	$userGroupSearch[$z]->name=htmlCode($userGroupSearch[$z]->name);
      }
      else
      {
       //$userGroupSearch[$z]->name=nameFilter($userGroupSearch[$z]->username,16);
          $userGroupSearch[$z]->name=htmlCode($userGroupSearch[$z]->username);
      }

      $userGroupSearch[$z]->profile_pic=profilePic($userGroupSearch[$z]->profile_pic); 
       $userGroupSearch[$z]->aboutme=nameFilter(htmlCode($userGroupSearch[$z]->aboutme),30);

    }
	echo '{"userGroupSearch": ' . json_encode($userGroupSearch) . '}';	
	}
	$db = null;
	
}
	
} catch(PDOException $e) {
	echo '{"error":{"text56":'. $e->getMessage() .'}}'; 
}
}

What is your problem exactly ?, please explain …!, what exactly you want? , how can you execute your php function is .ts file ?

i call the provider (auth-service.ts) and then the php function

auth-service

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

let apiUrl = "http://localhost/PHP-Slim-Restful1/api/";

@Injectable()
export class AuthService {

  constructor(public http: Http) {
    console.log('Hello AuthService Provider');
  }

  postData(credentials, type){

    return new Promise((resolve, reject) =>{
      let headers = new Headers();
      this.http.post(apiUrl+type, JSON.stringify(credentials), {headers: headers}).
      subscribe(res =>{
        resolve(res.json());
      }, (err) =>{
        reject(err);
      });

    });

  }

}


 allArtists() {
    this.common.presentLoading();
    this.authService.postData(this.userPostData, "newsFeed").then(

        result => {
            this.resposeData = result;
            if (this.resposeData.friendsNewsFeed) {
                this.common.closeLoading();
                this.dataSet = this.resposeData.friendsNewsFeed;
                console.log(this.dataSet);

            } else {
                console.log("No access");
            }
        },
        err => {
            //Connection failed message
        }
    );
}

home.ts (**newsfeed** is the php function i call from PHP-Restful)

I don’t know how else to explain it sorry. I want to return results from a php funcion in here

this.items = [
{ title: ‘one’ },
{ title: ‘two’ },
{ title: ‘three’ },
{ title: ‘four’ },
{ title: ‘five’ },
{ title: ‘six’ }
];

Okay now i got,Please use proper terminlogy of restful call , is the auth service required coz it you will have to make two calls , which involves chaining of promises.

Are you talking about rendering the page with the returned data …??

Yes i would like to render the returned dat on the searchPage.

I already send you the authservice.ts.
Then i call the Auth Service on app.module.ts

  providers: [
    StatusBar,
    SplashScreen,Camera,AuthService,SplitPane,Common,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
      AuthserviceProvider
  ]
})
export class AppModule {}

And then i call it on home.ts to return the UserData

The whole home.ts file

import { Component, ViewChild } from "@angular/core";
import { NavController, Platform, App, MenuController, AlertController } from "ionic-angular";
import { AuthService } from "../../providers/auth-service";
import { Common } from "../../providers/common";
import { Camera, CameraOptions } from "@ionic-native/camera";
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

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

import { UploadPage } from '../upload/upload';
import { SearchPage } from '../search/search';
import { UserPage } from '../userProfile/userProfile';
import { MediaPage } from '../mediaProfile/mediaProfile';


@Component({ selector: "page-home", templateUrl: "home.html" })
export class HomePage {
    data: any = {};
    @ViewChild("updatebox") updatebox;
    public userDetails: any;
    public resposeData: any;
    public dataSet: any;
    public noRecords: boolean;
    rootPage: any = HomePage;
      pages: Array<{ title: string, component: any }>;
    userPostData = {
        uid: "",
        token: "",
        username: "",
        bio: "",
        profile_pic:"",
        message: "",
        msg_id: "",
        title: "",
        description: "",
        media_pic: "",
        created: "",
        uid_fk:""
    };

    constructor(
        public common: Common,
        public navCtrl: NavController,
        public app: App,
        public menu: MenuController,
        public authService: AuthService,
        platform: Platform,
        statusBar: StatusBar,
        splashScreen: SplashScreen
    ) {
        const data = JSON.parse(localStorage.getItem("userData"));
        this.userDetails = data.userData;
        this.userPostData.uid = this.userDetails.uid;
        this.userPostData.token = this.userDetails.token;
        this.userPostData.username = this.userDetails.username;
        this.userPostData.msg_id = this.userDetails.msg_id;
        this.userPostData.message = this.userDetails.message;
        this.userPostData.title = this.userDetails.title;
        this.userPostData.description = this.userDetails.description;
        this.userPostData.media_pic = this.userDetails.media_pic;
        this.userPostData.created = this.userDetails.created;
        this.userPostData.profile_pic = this.userDetails.profile_pic;
        this.userPostData.bio = this.userDetails.bio;
        this.noRecords = false
        this.allArtists();
    }

    UploadPage() {
        this.navCtrl.push(UploadPage);
    }

    SearchPage() {
        this.navCtrl.push(SearchPage);
    }

    HomePage() {
        this.navCtrl.push(HomePage);
    }
    

    allArtists() {
        this.common.presentLoading();
        this.authService.postData(this.userPostData, "newsFeed").then(

            result => {
                this.resposeData = result;
                if (this.resposeData.friendsNewsFeed) {
                    this.common.closeLoading();
                    this.dataSet = this.resposeData.friendsNewsFeed;
                    console.log(this.dataSet);

                } else {
                    console.log("No access");
                }
            },
            err => {
                //Connection failed message
            }
        );
    }

    UserPage(uid_fk, username, bio, profile_pic) {
        this.navCtrl.push(UserPage, { uid_fk: uid_fk, username: username, bio: bio, profile_pic: profile_pic });
    }
    
    MediaPage(msg_id, message, title, description, media_pic) {
        this.navCtrl.push(MediaPage, { msg_id: msg_id, message: message, title: title, description: description, media_pic: media_pic });
    }


    converTime(time) {
        let a = new Date(time * 1000);
        return a;
    }

    backToWelcome() {
        const root = this.app.getRootNav();
        root.popToRoot();
    }



    logout() {
        //Api Token Logout

        localStorage.clear();
        setTimeout(() => this.backToWelcome(), 1000);
    }
}

thats all the script i use

that data are returned ok on home.html but i dont know how to do the SearchPage

my search ts code:

getItems(ev){
let val = ev.target.value;

this.filterz = this.displayContact;
this.contacts.forEach((arr,index)=>{
this.filterz[index].fullName = arr.userContact.firstName + ’ ’ + arr.userContact.lastName;
return this.filterz[index];
})
if (val && val.trim() != ‘’) {
this.filterz = this.filterz.filter((item) => {
return (item.name.toLowerCase().includes(val.toLowerCase()));
})
}
console.log(this.filterz);
}

my html code:
//
“//”
"// "
// <ion-searchbar (ionInput)=“getItems($event)”>
// <ion-item *ngFor=“let cont of filterz” (click)=“onSelect(cont,$event)”>
//
//

{{cont.name}}

//

{{cont.email}}


// <input type=“checkbox” [checked]=“cont.selected” color=“toolbar” item-end />
//
//

//

  • if this.dataSet is an array then use array function:

    this.dataset.forEach((valueOfEachElement,index,andWholeArray)=>{
    this.filterItem.push(valueofEachElement);
    })

Some error while showing html code

Where do i return the JSON? The $userGroupSearch

I mean where i put the code to return from PHP funtion like this?
userMostMedia is the PHP function.

this.authService.postData(this.userPostData, “usersMostMedia”).then(

Where did you get this.displayContact from

that is my variable which saves my online contacts . the code is simple to understand, the filter function shows only those elements which contains the searchbar string ,the first filter function concats the first name and last name , the next filter function matchs the content of search string with all entries.

i understand that but i can’t figure out how to connect with auth-service.ts? And to call a certain php function from api?

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

let apiUrl = "http://localhost/PHP-Slim-Restful1/api/";

@Injectable()
export class AuthService {

  constructor(public http: Http) {
    console.log('Hello AuthService Provider');
  }

  postData(credentials, type){

    return new Promise((resolve, reject) =>{
      let headers = new Headers();
      this.http.post(apiUrl+type, JSON.stringify(credentials), {headers: headers}).
      subscribe(res =>{
        resolve(res.json());
      }, (err) =>{
        reject(err);
      });

    });

  }

}

Can you post the whole ts files (search.ts, authservice …)?

what i mean is can you post the whole .ts file where it shows where this.displayContact is being initialized? and your php function. Please.
Thanks in advance

Can you please post all search.ts code? I mean where displayContact is initialised? The whole file so i can solve this?

Thanks

This is my code so far…

search.ts

 import { Component, ViewChild } from "@angular/core";
import { NavController, Platform, App, MenuController, AlertController } from "ionic-angular";
import { AuthService } from "../../providers/auth-service";
import { Common } from "../../providers/common"; 
import { Camera, CameraOptions } from "@ionic-native/camera";
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

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


@Component({ selector: "page-search", templateUrl: "search.html" })
export class SearchPage {
filtereditems: any;
searchTerm: string = '';
public userDetails: any;
public resposeData: any;
public userSet: any;
public mediaSet: any;
public noRecords: boolean;
userPostData = {
   uid: "",
   token: "",
   username: "",
   bio: ""
    };

constructor(
   public common: Common,
   public navCtrl: NavController,
   public app: App,
   public menu: MenuController,
   public authService: AuthService,
   platform: Platform,
   statusBar: StatusBar,
   splashScreen: SplashScreen
 ) {

   const data = JSON.parse(localStorage.getItem("userData"));
   this.userDetails = data.userData;
   this.userPostData.uid = this.userDetails.uid;
   this.userPostData.token = this.userDetails.token;
   this.userPostData.username = this.userDetails.username;
   this.userPostData.bio = this.userDetails.bio;
   this.noRecords = false
   this.filterItems();
}


filterItems() {
    console.log(this.searchTerm);
    this.filtereditems = this.items.filter((item) => {


        this.authService.postData(this.userPostData, "usersMostMedia").then(

            result => {
                this.resposeData = result;
                if (this.resposeData.mostUsers) {
                    this.userSet = this.resposeData.mostUsers;
                    console.log(this.userSet);
                    return item.title.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1;
                } else {
                    console.log("No access");
                }
            },
            err => {
                //Connection failed message
            }
        );
    });


}

}

What i am doing wrong?

You should understand the filter function first… get data from json array put them in items and then filter that items to filteredItems

That’s what i am not understaning how to pass this.displayContact? I am getting an error that item.username is not defined