Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
Ionic2

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
Miscellaneou$

Makers vs Consumers – don’t hate, donate

When was the last time you contributed to some open source project? Did you ever even click on that little star on Github? Or, when was the last time you showed support to the people who work for free on these projects that you take for granted and use daily for your (commercial) projects!?

A lot of people in the software development world started saying $hit about the makers of certain open source projects. That is really not the route you want to take as a professional, so please stop it. I really won’t go any deeper than that, because if they don’t understand that that’s not nice/moral/right, then I see no hope for them to ever grow as persons or developers.

If you indeed find something that’s lacking, instead of complaining

make a freaking meaningful pull request!

For all those who are complaining that “it’s hard to keep up with all the change in the web development world with all these new tools and hundred ways of doing the same thing” I only have one thing to say:

You don’t need to jump into every new framework that comes out. However, you do need to (in your chosen field) adapt, grow, or walk away. It’s really not for everyone. If you’re not willing to daily invest time to hone your skills as a developer then I have to conclude that you came into this field for all the wrong reasons!

Below is the awesome video on this topic by the awesome Mattias P Johansson (@mpjme). You should check out his videos, he has a really good series (presented in a fresh and fun way) about JavaScript.

All in all, dear people:

don’t hate, donate!

And, dear makers, don’t get discouraged, because without you these ungrateful consumers will, well, be worthlessly lost…

#Makers vs #Consumers – don't hate, donate. Eye opening​ video by @mpjme https://t.co/2IxIvzYMgq

— Nikola Brežnjak (@HitmanHR) January 19, 2016

Ionic, Stack Overflow

Ionic – how to handle when external api server is offline?

In this StackOverflow question I answered how to handle when external API server is offline.

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

As you may know, I’m really into Ionic framework lately and am helping out on StackOverflow with the knowledge I gained so far with the framework. I’m currently #3 in the top All time answerers list.

I answered this question by user Rflujowa:

I’m writing a app in ionic. The app relies on external api’s. I’ve made multiple functions to test the connection, to my own server, and my own server handles the api calls. My own server is needed for this because of ip-whitelistening.

All works well, but now i want to disable the application if the result from my own server is false. I make a call to test the connection everytime the app starts.

What is the best way to handle this with angular/ionic?

1 thought i had myself is to redirect to a landingpage, if no connection is available.

Any tips are welcome.

My answer was:

Yes, basically what you planned to do is OK.

So, just after your app loads up, check if the connection is available (you can read more about how to do that in my detailed post How to check network information change with Ionic framework), and if not then you can change the state to some page where it would clearly let the user know that “Currently the link to the server is not working” (or some better notification).

Also, probably you would want to put a refresh button on that page, so that one could click it and the whole availability process would be checked again (basically same as if someone restarted your app).

Hope this helps.

How to handle when external #API server is offline in @ionicframework? https://t.co/FSGt6AoXCQ

— Nikola Brežnjak (@HitmanHR) January 19, 2016

Recent posts

  • Discipline is also a talent
  • Play for the fun of it
  • The importance of failing
  • A fresh start
  • Perseverance

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (35)
  • Daily Thoughts (77)
  • Go (3)
  • iOS (5)
  • JavaScript (127)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (2)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (77)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (40)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak