Posting data from Ionic 3 app to a PHP server

TL;DR

This is the simplest example which shows how to POST data from an Ionic 3 app to a PHP server.

The tutorial covering the Ionic version 1 can be found here, and the tutorial covering the Ionic version 2 can be found here.

Quickstart

To see it in action:

    1. Clone the finished project from Github
    2. Make sure you’ve got the newest Ionic CLI (see below for instructions)
    3. Run ionic serve
    4. You should see something like this:
      ionic2ServerPost

If you want to make it work from your server:

  1. Make sure you’ve got the newest Ionic CLI (see below for instructions)
  2. Clone the finished project from Github
  3. Upload the PHP/api.php file to your server
  4. In the src/pages/home/home.ts file adjust the link variable (line #21) to point to your server
  5. Run ionic serve

Getting started with Ionic 3

After neglecting Ionic 3 (and for the most part Ionic 2) for far too long due to the overburdening work I still have on my Ionic 1 apps, I finally got some time to take a look at Ionic 3 and update the most popular post about Ionic on my blog, so here you go and enjoy.

In general, from me playing just a bit with Ionic 3, I have to say I love it, so expect some more posts about it soon-ish…

To install the Ionic SDK and create Ionic 3 projects, you need to install the latest Ionic CLI:

npm install -g ionic

You don’t need to worry about this messing up your current ionic CLI since the new one still works with old Ionic 1 projects.

Just for reference, here’s what my ionic info says now:

$> ionic info 

global packages:

    @ionic/cli-utils : 1.4.0
    Ionic CLI        : 3.4.0

local packages:

    @ionic/app-scripts              : 1.3.7
    @ionic/cli-plugin-ionic-angular : 1.3.1
    Ionic Framework                 : ionic-angular 3.4.2

System:

    Node       : v8.0.0
    OS         : macOS Sierra
    Xcode      : Xcode 8.3.3 Build version 8E3004b 
    ios-deploy : 1.9.1 
    ios-sim    : 5.0.13 
    npm        : 5.0.1 

Step by step on how to create this yourself from scratch

  1. Create a new blank Ionic project with:
    ionic start Ionic3ServerSendTest blank
  2. Copy the following code to src/pages/home/home.html file:
    <ion-header>
     <ion-navbar>
     <ion-title>
     Ionic3 Server Send Test
     </ion-title>
     </ion-navbar>
    </ion-header>
    
    <ion-content padding>
     <ion-list>
     <ion-item>
     <ion-label floating>Username</ion-label>
     <ion-input type="text" name="username" [(ngModel)]="data.username"></ion-input>
     </ion-item>
    
     <button ion-button block (click)="submit()">Submit to server</button>
     </ion-list>
    
     <ion-card>
     <ion-card-header>
     Response
     </ion-card-header>
    
     <ion-card-content>
     <b>{{data.response}}</b>
     </ion-card-content>
     </ion-card>
    </ion-content>
    

    Here you basically created a form with an username input field and with a button which acts as a submit button.

    Once the button is clicked AngularJS should handle it within the submit() function which we will define in our src/pages/home/home.ts file (shown below).

    Input username uses  the new syntax for ng-model , and it binds to the variable data.username, so that you can then use it in your submit() function (shown below).

    Components are a bit different in Ionic 3 now, so I encourage you can take a look at the official documentation.

  3. On your server, create an api.php file with the following content:
    <?php
        //http://stackoverflow.com/questions/18382740/cors-not-working-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);
        }
    
    
        //http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined
        $postdata = file_get_contents("php://input");
        if (isset($postdata)) {
            $request = json_decode($postdata);
            $username = $request->username;
    
            if ($username != "") {
                echo "Server returns: " . $username;
            }
            else {
                echo "Empty username parameter!";
            }
        }
        else {
            echo "Not called properly with username parameter!";
        }
    ?>

    As you can see from the code, the first part is explained in detail in this StackOverflow question, and it basically solves the CORS issue that you would otherwise run into.

    The second part, explained in detail in this StackOverflow question,  deals with the way you POST data from Ionic to your PHP server. The gist is that since we POSTed in a JSON format, we have to json_decode  the data that comes to your PHP server.

  4. To the file src/pages/home/home.ts file copy the following content and adjust the link variable to point to the file on your server:
    import { Component } from '@angular/core';
    import { NavController } from 'ionic-angular';
    import { Http } from '@angular/http'; //https://stackoverflow.com/questions/43609853/angular-4-and-ionic-3-no-provider-for-http
    
    @Component({
     selector: 'page-home',
     templateUrl: 'home.html'
    })
    
    export class HomePage {
     data:any = {};
    
     constructor(public navCtrl: NavController, public http: Http) {
     this.data.username = '';
     this.data.response = '';
    
     this.http = http;
     }
    
     submit() {
     var link = 'http://nikola-breznjak.com/_testings/ionicPHP/api.php';
     var myData = JSON.stringify({username: this.data.username});
     
     this.http.post(link, myData)
     .subscribe(data => {
     this.data.response = data["_body"]; //https://stackoverflow.com/questions/39574305/property-body-does-not-exist-on-type-response
     }, error => {
     console.log("Oooops!");
     });
     }
    }

    As with the Ionic 2 tutorial, things have changed a lot since Ionic 1, but in Ionic 3 (if you come from Ionic 2) you shouldn’t have any problems. Anyways, practice makes perfect, so make sure you put in the hours of deliberate practice.

    In this file, we import the Http component from Angular. You can check out the link in the comment to learn that you also need to import and inject HttpModule in src/app/app.module.ts (two new lines that I’ve added are bolded):

    import { BrowserModule } from '@angular/platform-browser';
    import { ErrorHandler, NgModule } from '@angular/core';
    import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
    import { SplashScreen } from '@ionic-native/splash-screen';
    import { StatusBar } from '@ionic-native/status-bar';
    import { HttpModule} from '@angular/http';
    
    import { MyApp } from './app.component';
    import { HomePage } from '../pages/home/home';
    
    @NgModule({
     declarations: [
     MyApp,
     HomePage
     ],
     imports: [
     BrowserModule,
     IonicModule.forRoot(MyApp),
     HttpModule
     ],
     bootstrap: [IonicApp],
     entryComponents: [
     MyApp,
     HomePage
     ],
     providers: [
     StatusBar,
     SplashScreen,
     {provide: ErrorHandler, useClass: IonicErrorHandler}
     ]
    })
    export class AppModule {}

    Inside the HomePage class, we now have a constructor where we’re setting some default values. Important to note, see how we’re passing in Http via the constructor parameter.

    Inside the submit function we use the http service to post to our API endpoint with some data. Make note of how we use the subscribe function to handle data once it arrives. Also, make sure you check out the StackOverflow link in the comment as a solution of how to access plain text response.

  5. Run ionic serve  from the root directory of your Ionic app

That’s all folks, I hope this tutorial helps you in starting your journey towards Ionic3 & Angular4!

Written by Nikola Brežnjak