Posting data from Ionic 2 app to a PHP server

TL;DR

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

The tutorial covering the Ionic version 2 can be found here. The tutorial covering the Ionic version 3 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 beta 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 beta 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 app/pages/home/home.js file adjust the link variable (line #18) to point to your server
  5. Run ionic serve

Getting started with Ionic 2

By now you probably have heard that Ionic is in beta for its version 2, which closely follows Angular 2.

You can find a lot more Ionic 2 related tutorials on my friend Gajotres site.

To install the Ionic SDK and create Ionic 2 projects, you need to install the latest beta release:

npm install -g ionic@beta

You don’t need to worry about this messing up your current ionic CLI since the beta release has all the functionality to work with both V1 and V2 projects.

Step by step on how to create this yourself from scratch

  1. Create a new blank Ionic project with:
    ionic start Ionic2ServerSendTest blank --v2
  2. Copy the following code in app/pages/home/home.html file:
    <ion-navbar *navbar>
        <ion-title>
            Home
        </ion-title>
    </ion-navbar>
    
    <ion-content padding>
        <ion-list>
            <ion-input floating-label>
                <ion-label>Username</ion-label>
                <input type="text" name="username" [(ngModel)]="data.username">
            </ion-input>
    
            <button round 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.

    As you can see, the syntax is a bit different since Ionic2 uses Angular2. Once the button is clicked AngularJS should handle it within the submit() function which we will define in our app/pages/home/home.js file (shown below).

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

    Also, components are a bit different in Ionic now, and 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. In app/pages/home/home.js file adjust the link variable to point to the file on your server
  5. In app/pages/home/home.js file copy the following content:
    import {Page} from 'ionic/ionic';
    import {Http} from 'angular2/http';
    
    @Page({
        templateUrl: 'build/pages/home/home.html',
    })
    
    export class HomePage {
        constructor(http: Http) {
            this.data = {};
            this.data.username = '';
            this.data.response = '';
    
            this.http = http;
        }
    
        submit() {
            var link = 'http://nikola-breznjak.com/_testings/ionicPHP/api.php';
            var data = JSON.stringify({username: this.data.username});
            
            this.http.post(link, data)
            .subscribe(data => {
                this.data.response = data._body;
            }, error => {
                console.log("Oooops!");
            });
      }
    }

    Again, as I said, some (a lot) of things have changed in Angular 2, and at first glance you really may not like it (tbh, I know I didn’t). But, that will change with usage, so no worries.

    First thing that we do here is we import Page and Http components from Ionic and Angular, respectively. Then we’re setting the Page templateUrl to our home.html file.

    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. Again, I won’t go into details of using this, as I mentioned you can take a look at a lot more in depth tutorials on Gajotres.

    Inside the submit function we use the http service to post to our API endpoint with some data. Make note of how we use subscribe to handle data once it  arrives.

  6. Run ionic serve  from the root directory of your Ionic app
  7. Hope this tutorial helps you in starting your journey towards (Ionic + Angular)_2
Written by Nikola Brežnjak