Get response from a HTTP page


#1

Hello,
First of all, thanks you for the help, i’m sorry if my english isn’t perfect because i’m french.

So, i try to get a response from a HTTP page in PHP with this @ionic-native/http

My app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { Accueil } from '../pages/accueil/accueil';
import { VotrePhotographe } from '../pages/photographe/photographe';
import { GaleriePage } from '../pages/galerie/galerie';
import { TarifsPage } from '../pages/tarifs/tarifs';
import { ContactPage } from '../pages/contact/contact';
import { EspaceClient } from '../pages/espace-client/espace-client';
import { GaleriePrive } from '../pages/galerie-prive/galerie-prive';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

/* Pour les email */
import { Camera } from '@ionic-native/camera';
import { EmailComposer } from '@ionic-native/email-composer';

/* Connexion SQL */

//import { HttpModule } from '@angular/http';
import { HTTP } from '@ionic-native/http';

@NgModule({
  declarations: [
    MyApp,
    Accueil,
    VotrePhotographe,
    GaleriePage,
    TarifsPage,
    ContactPage,
    EspaceClient,
    GaleriePrive
  ],
  imports: [
    BrowserModule, 
    //HttpClientModule,
    //HttpModule,
    IonicModule.forRoot(MyApp),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    Accueil,
    VotrePhotographe,
    GaleriePage,
    TarifsPage,
    ContactPage,
    EspaceClient,
    GaleriePrive
  ],
  providers: [
    StatusBar,
    SplashScreen,
    Camera,
    EmailComposer,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    HTTP
  ]
})
export class AppModule {}

My espace-client.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { GaleriePrive } from '../galerie-prive/galerie-prive';
//import { EspaceClient } from '../espace-client/espace-client';
import { HTTP } from '@ionic-native/http';

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

@IonicPage()
@Component({
  selector: 'page-espace-client',
  templateUrl: 'espace-client.html',
})
export class EspaceClient {

  constructor(public navCtrl: NavController, public navParams: NavParams, private http: HTTP) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad EspaceClient');
  }

  login() {
    this.navCtrl.push(GaleriePrive);  
  }

  try() {
    this.http.get('http://www.api.les-cherubins-photographie.fr/index.php?action=CheckUserExist&user=Nicolas', {}, {})
    .then(data => {

      console.log(data.status);
      console.log(data.data); // data received by server
      console.log(data.headers);

    })
    .catch(error => {

      console.log(error.status);
      console.log(error.error); // error message as string
      console.log(error.headers);

    });
  }
  
}

And my espace-client.html

<!--
  Generated template for the EspaceClientPage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar>
    <!-- Ouvrir nav bar-->
      <button ion-button menuToggle>
          <ion-icon name="menu"></ion-icon>
        </button>
    <!-- FIN DE NAV BAR -->

    <ion-title>Espace Client</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding id="PageEspaceClient">

  <ion-list>

    <ion-item>
      <ion-label stacked>Identifiant</ion-label>
      <ion-input type="user" value=""></ion-input>
    </ion-item>
  
    <ion-item>
      <ion-label stacked>Mot de passe</ion-label>
      <ion-input type="password"></ion-input>
    </ion-item>
  
  </ion-list>

  <button ion-button full class="Button" (click)="login()">Se connecter</button>
  <button ion-button full class="Button" (click)="try()">TRY</button>

</ion-content>

My index.php (API)

<?php

ini_set('display_errors', 'on');

/* DATABASE */
$dbhost = "XXX";
$dbname = "XXX";
$dbuser = "XXX";
$dbpass = "XXX";

try {
	$bdd = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
} catch(Exception $e) {
    die('Erreur : '.$e->getMessage());
}

//$action = $_GET['action'];

if (isset($_GET['action'])) {
	$action = $_GET['action'];
	$nombre = strlen($_GET['action']);

	if ($nombre >= 1) {
		switch ($action) {

			/* API CHECK IF THE USER EXIST */

			case 'CheckUserExist':
				if (isset($_GET['user'])) {
					$username = $_GET['user'];
					$query = 'SELECT username FROM users WHERE username = "'. $username . '"';
					$query_res = $bdd->query($query);
					$count= count($query_res->fetchAll());
					if($count > 0){
						$result = 'USER_EXIST';
					} else {
						$result = 'ERROR:USER_DO_NOT_EXIST';
					}
				} else {
					$result = 'ERROR:USER_NOT_DEFINIE';
				}
				break;

			/* BY DEFAULT IF NO THINGS IS DEFINE, IT RESULT AN ERROR */

			default:
				$result = 'ERROR:ACTION_UNKNOW';
		}
	} else {
		$result = 'ERROR:ACTION_NULL';
	}

} else {
	$result = 'ERROR:ACTION_NOT_DEFINIE';
}

echo $result;
?>

So, the problem is, when i press the button “TRY” for see in if ionic can get the HTTP page the result is this:

[12:46:03]  console.log: null
[12:46:03]  console.log: null
[12:46:03]  console.log: null

So i think the connection don’t work, but i don’t know why ?
I’m not realy good in php, and i’m learning ionic so, it’s hard ^^
Thx if you can help me :smiley:


#2

So ?? No one have any idea ? :cry:


#3

Hi,

I just suggest the http post and get service using ionic with by blog link…

https://ionicblog.quora.com/Http-services-with-promises-call-both-ionic-angular-5-angualr-cli


#4
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
export class class_name
{
constructor(public http: Http){}
  ionViewDidLoad() {
    this.http.get(url)
	    .map(res => res.json())
	    .subscribe(statedata => {
	      this.states = statedata;
       console.log("States : "+this.states);
      });
  }
}

#5

Thx i will check this !


#6

Thx for help ! But there is an error :confused:
[ts] La propriété 'states' n'existe pas sur le type 'EspaceClient'.

So I have add

public states: any

But there is still an error :confused:

Error: Can't resolve all parameters for EspaceClient: ([object Object], [object Object], [object Object], ?).
    at syntaxError (http://localhost:8100/build/vendor.js:78159:34)
    at CompileMetadataResolver._getDependenciesMetadata (http://localhost:8100/build/vendor.js:93374:35)
    at CompileMetadataResolver._getTypeMetadata (http://localhost:8100/build/vendor.js:93209:26)
    at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (http://localhost:8100/build/vendor.js:92694:24)
    at CompileMetadataResolver._getEntryComponentMetadata (http://localhost:8100/build/vendor.js:93522:45)
    at http://localhost:8100/build/vendor.js:92992:55
    at Array.map (<anonymous>)
    at CompileMetadataResolver.getNgModuleMetadata (http://localhost:8100/build/vendor.js:92992:18)
    at JitCompiler._loadModules (http://localhost:8100/build/vendor.js:112079:87)
    at JitCompiler._compileModuleAndComponents (http://localhost:8100/build/vendor.js:112040:36)

#7

Please, share your code.


#8
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { GaleriePrive } from '../galerie-prive/galerie-prive';
//import { EspaceClient } from '../espace-client/espace-client';
//import { HTTP } from '@ionic-native/http';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@IonicPage()
@Component({
  selector: 'page-espace-client',
  templateUrl: 'espace-client.html',
})
export class EspaceClient {

  constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http, public states: any) {
  }

  /*ionViewDidLoad() {
    console.log('ionViewDidLoad EspaceClient');
  }*/

  login() {
    this.navCtrl.push(GaleriePrive);  
  }

  try() {
    this.http.get('http://www.api.les-cherubins-photographie.fr/index.php?action=CheckUserExist&user=Nicolas')
      .map(res => res.json())
      .subscribe(statedata => {
      this.states = statedata;
      console.log("States : "+ this.states);
    });
  }
  
}

#9

try this, remove try() block and copy the code of try() in ionViewDidLoad().

ionViewDidLoad() {
  this.http.get('http://www.api.les-cherubins-photographie.fr/index.php? 
  action=CheckUserExist&user=Nicolas')
      .map(res => res.json())
      .subscribe(statedata => {
      this.states = statedata;
      console.log("States : "+ this.states);
    });
}

Your API has some error, it gives…
Failed to load http://www.api.les-cherubins-photographie.fr/index.php?action=CheckUserExist&user=Nicolas: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8100’ is therefore not allowed access.


#10

I don’t have any error when i go on it

Still the same error,

espace-client.ts

import { Component } from '@angular/core';
import { IonicPage, NavController} from 'ionic-angular';
import { GaleriePrive } from '../galerie-prive/galerie-prive';
//import { EspaceClient } from '../espace-client/espace-client';
//import { HTTP } from '@ionic-native/http';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@IonicPage()
@Component({
  selector: 'page-espace-client',
  templateUrl: 'espace-client.html',
})
export class EspaceClient {

  constructor(public navCtrl: NavController, public http: Http, public states: any) {
  }

  ionViewDidLoad() {
    this.http.get('http://www.api.les-cherubins-photographie.fr/index.php?action=CheckUserExist&user=Nicolas')
      .map(res => res.json())
      .subscribe(statedata => {
      this.states = statedata;
      console.log("States : "+ this.states);
    });
  }

  login() {
    this.navCtrl.push(GaleriePrive);  
  }
  
}

espace-client.html

<!--
  Generated template for the EspaceClientPage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar>
    <!-- Ouvrir nav bar-->
      <button ion-button menuToggle>
          <ion-icon name="menu"></ion-icon>
        </button>
    <!-- FIN DE NAV BAR -->

    <ion-title>Espace Client</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding id="PageEspaceClient">

  <ion-list>

    <ion-item>
      <ion-label stacked>Identifiant</ion-label>
      <ion-input type="user" value=""></ion-input>
    </ion-item>
  
    <ion-item>
      <ion-label stacked>Mot de passe</ion-label>
      <ion-input type="password"></ion-input>
    </ion-item>
  
  </ion-list>

  <button ion-button full class="Button" (click)="login()">Se connecter</button>
  <button ion-button full class="Button" (click)="ionViewDidLoad()">TRY</button>

</ion-content>

Error:

Error
Close
Runtime Error
Can't resolve all parameters for EspaceClient: ([object Object], [object Object], ?).
Stack
Error: Can't resolve all parameters for EspaceClient: ([object Object], [object Object], ?).
    at syntaxError (http://localhost:8100/build/vendor.js:78159:34)
    at CompileMetadataResolver._getDependenciesMetadata (http://localhost:8100/build/vendor.js:93374:35)
    at CompileMetadataResolver._getTypeMetadata (http://localhost:8100/build/vendor.js:93209:26)
    at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (http://localhost:8100/build/vendor.js:92694:24)
    at CompileMetadataResolver._getEntryComponentMetadata (http://localhost:8100/build/vendor.js:93522:45)
    at http://localhost:8100/build/vendor.js:92992:55
    at Array.map (<anonymous>)
    at CompileMetadataResolver.getNgModuleMetadata (http://localhost:8100/build/vendor.js:92992:18)
    at JitCompiler._loadModules (http://localhost:8100/build/vendor.js:112079:87)
    at JitCompiler._compileModuleAndComponents (http://localhost:8100/build/vendor.js:112040:36)
Ionic Framework: 3.9.2
Ionic App Scripts: 3.1.9
Angular Core: 5.2.9
Angular Compiler CLI: 5.2.9
Node: 8.11.1
OS Platform: Windows 10
Navigator Platform: Win32
User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36

i think the problem come from this:
public states: any

I think i should replace the any but i don’t know with what


#11

Try this one, declare variable states before counstructor and remove + from console.log because this.states contains object and we can’t concatinate object with string.

states:any = [];
console.log("States : ", this.states);

#12

Thanks we are on the good way, but still an error (In the console)

[OK] Development server running!
     Local: http://localhost:8100
     External: http://192.168.1.16:8100
     DevApp: Cherubins@8100 on DESKTOP-C9SA2I7

[11:58:27]  console.log: Angular is running in the development mode. Call enableProdMode() to enable the production
            mode.
[11:58:27]  console.warn: Native: tried calling StatusBar.styleDefault, but Cordova is not available. Make sure to
            include cordova.js or run in a device/simulator
[11:58:27]  console.warn: Native: tried calling SplashScreen.hide, but Cordova is not available. Make sure to include
            cordova.js or run in a device/simulator
[11:58:28]  lint finished in 2.96 s
[11:58:38]  console.log: Angular is running in the development mode. Call enableProdMode() to enable the production
            mode.
[11:58:38]  console.warn: Native: tried calling StatusBar.styleDefault, but Cordova is not available. Make sure to
            include cordova.js or run in a device/simulator
[11:58:38]  console.warn: Native: tried calling SplashScreen.hide, but Cordova is not available. Make sure to include
            cordova.js or run in a device/simulator
[11:58:41]  console.error: ERROR [object Object]
[11:58:42]  console.error: ERROR [object Object]
[11:58:43]  console.error: ERROR [object Object]
[11:58:46]  console.error: ERROR [object Object]

espace-client.ts

import { Component } from '@angular/core';
import { IonicPage, NavController } from 'ionic-angular';
import { GaleriePrive } from '../galerie-prive/galerie-prive';
//import { EspaceClient } from '../espace-client/espace-client';
//import { HTTP } from '@ionic-native/http';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@IonicPage()
@Component({
  selector: 'page-espace-client',
  templateUrl: 'espace-client.html',
})
export class EspaceClient {
  states:any = [];

  constructor(public navCtrl: NavController, public http: Http) {
  }

  ionViewDidLoad() {
    this.http.get('http://www.api.les-cherubins-photographie.fr/index.php?action=CheckUserExist&user=Nicolas')
      .map(res => res.json())
      .subscribe(statedata => {
      this.states = statedata;
      console.log("States : ", this.states);
    });
  }

  login() {
    this.navCtrl.push(GaleriePrive);  
  }
  
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { Accueil } from '../pages/accueil/accueil';
import { VotrePhotographe } from '../pages/photographe/photographe';
import { GaleriePage } from '../pages/galerie/galerie';
import { TarifsPage } from '../pages/tarifs/tarifs';
import { ContactPage } from '../pages/contact/contact';
import { EspaceClient } from '../pages/espace-client/espace-client';
import { GaleriePrive } from '../pages/galerie-prive/galerie-prive';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

/* Pour les email */
import { Camera } from '@ionic-native/camera';
import { EmailComposer } from '@ionic-native/email-composer';

/* Connexion SQL */

//import { HttpModule } from '@angular/http';
//import { HTTP } from '@ionic-native/http';
//import { Http } from '@angular/http';
//import { HttpModule } from '@angular/http';
import { HttpModule } from '@angular/http';

@NgModule({
  declarations: [
    MyApp,
    Accueil,
    VotrePhotographe,
    GaleriePage,
    TarifsPage,
    ContactPage,
    EspaceClient,
    GaleriePrive
  ],
  imports: [
    BrowserModule, 
    //HttpClientModule,
    HttpModule,
    //Http,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    Accueil,
    VotrePhotographe,
    GaleriePage,
    TarifsPage,
    ContactPage,
    EspaceClient,
    GaleriePrive
  ],
  providers: [
    StatusBar,
    SplashScreen,
    Camera,
    EmailComposer,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

(I have edit the app.module.ts for add the HttpModule)


#13

comment console and execute again…

//console.log("States : ", this.states);


#14

Nothings happend :confused:


#15

I’ll execute and let you know what is the error…


#16

You want i upload everythings and i give it to you ?


#17

try this code,

import { Component } from ‘@angular/core’;

import { NavController, NavParams } from ‘ionic-angular’;

import { Http } from ‘@angular/http’;

import { Observable} from ‘rxjs/Observable’;

import ‘rxjs/Rx’;

//import ‘rxjs/add/operator/map’;

@Component({

selector: ‘page-demo’,

templateUrl: ‘demo.html’,

})

export class DemoPage {

states:any=[];

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

}

ionViewDidLoad() {

console.log('ionViewDidLoad DemoPage');

this.http.get('[http://www.api.les-cherubins-photographie.fr/index.php?action=CheckUserExist&user=Nicolas](http://www.api.les-cherubins-photographie.fr/index.php?action=CheckUserExist&user=Nicolas)')

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

  .subscribe(statedata => {

  this.states = statedata;

  console.log("States : ", this.states);

});

}

}


#18

You have declared states in constructor, that’s why it shows error.


#19

Still error…

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Http } from '@angular/http';
//import { Observable} from 'rxjs/Observable';
import { GaleriePrive } from '../galerie-prive/galerie-prive';
import 'rxjs/Rx';

//@IonicPage()
@Component({
  selector: 'page-espace-client',
  templateUrl: 'espace-client.html',
})
export class EspaceClient {
  states:any=[];

  constructor(public navCtrl: NavController, public navParams: NavParams,public http: Http) {}

  ionViewDidLoad() {
    console.log('ionViewDidLoad DemoPage');
    this.http.get('[http://www.api.les-cherubins-photographie.fr/index.php?action=CheckUserExist&user=Nicolas](http://www.api.les-cherubins-photographie.fr/index.php?action=CheckUserExist&user=Nicolas)')
      .map(res => res.json())
      .subscribe(statedata => {
      this.states = statedata;
      console.log("States : ", this.states);
    });
  }

  login() {
    this.navCtrl.push(GaleriePrive);  
  }
  
}

Logs in console:

[19:49:54]  console.log: Angular is running in the development mode. Call enableProdMode() to enable the production
            mode.
[19:49:54]  console.warn: Native: tried calling StatusBar.styleDefault, but Cordova is not available. Make sure to
            include cordova.js or run in a device/simulator
[19:49:54]  console.warn: Native: tried calling SplashScreen.hide, but Cordova is not available. Make sure to include
            cordova.js or run in a device/simulator
[19:50:14]  console.log: ionViewDidLoad DemoPage
[19:50:14]  console.error: ERROR [object Object]
[19:50:15]  console.log: ionViewDidLoad DemoPage
[19:50:15]  console.error: ERROR [object Object]

#20

i don’t get any error… I only got the error that api dont have access control… apart from in TS its working fine.