Sie sind auf Seite 1von 13

Posting data from Ionic app to PHP server

TL;DR
This is the simplest example which shows how to POST data from
an Ionic 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. Run ionic serve
1. You should see something like this:
If you want to make it work from your server:

1. Clone the finished project from Github


2. Upload the PHP/api.php file to your server
3. In the www/js/app.js file adjust the link variable to point to your
server
4. Run ionic serve

Step by step on how to create this yourself from scratch


1. Create a new blank Ionic project with:

1 ionic start ionicServerSendTest blank


2. Copy the following code (you’ll already have the .run() part,
the .controller() part is novelty here) in www/js/app.js file:

1 // Ionic Starter App


2
3 // angular.module is a global place for creating, registering and retrieving Angular
4 modules
5 // 'starter' is the name of this angular module example (also set in a <body>
6 attribute in index.html)
7 // the 2nd parameter is an array of 'requires'
8 angular.module('starter', ['ionic'])
9
10 .run(function($ionicPlatform) {
11 $ionicPlatform.ready(function() {
12 // Hide the accessory bar by default (remove this to show the accessory bar
13 above the keyboard
14 // for form inputs)
15 if (window.cordova && window.cordova.plugins.Keyboard) {
16 cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
17 }
18 if (window.StatusBar) {
19 StatusBar.styleDefault();
20 }
21 });
22 })
23
24 .controller('AppCtrl', function($scope, $http) {
25 $scope.data = {};
26
27 $scope.submit = function(){
28 var link = 'http://nikola-breznjak.com/_testings/ionicPHP/api.php';
29
30 $http.post(link, {username : $scope.data.username}).then(function (res){
31 $scope.response = res.data;
});
};
});
3. On your server, create a api.php file with the following content:

<?php
1 //http://stackoverflow.com/questions/18382740/cors-not-working-php
2 if (isset($_SERVER['HTTP_ORIGIN'])) {
3 header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
4 header('Access-Control-Allow-Credentials: true');
5 header('Access-Control-Max-Age: 86400'); // cache for 1 day
6 }
7
8 // Access-Control headers are received during OPTIONS requests
9 if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
10
11 if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
12 header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
13
14 if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
15 header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTRO
16 L_REQUEST_HEADERS']}");
17
18 exit(0);
19 }
20
21
22 //http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-
23 undefined
24 $postdata = file_get_contents("php://input");
25 if (isset($postdata)) {
26 $request = json_decode($postdata);
27 $username = $request->username;
28
29 if ($username != "") {
30 echo "Server returns: " . $username;
31 }
32 else {
33 echo "Empty username parameter!";
34 }
35 }
36 else {
37 echo "Not called properly with username parameter!";
38 }
?>
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 (basically an AngularJS
app) to your PHP server. The gist is that AngularJS POSTs by default in
a JSON format, and thus you have tojson_decode the data that
comes to your PHP server.
4. In www/js/app.js file adjust the link variable to point to the file on
your server
5. In www/index.html file copy the following content:

<!DOCTYPE html>
<html>
1 <head>
2 <meta charset="utf-8">
3 <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-
4 scalable=no, width=device-width">
5 <title></title>
6 <link href="lib/ionic/css/ionic.css" rel="stylesheet">
7 <link href="css/style.css" rel="stylesheet">
8 <!-- IF using Sass (run gulp sass first), then uncomment below and remove the
9 CSS includes above
10 <link href="css/ionic.app.css" rel="stylesheet">
11 -->
12 <!-- ionic/angularjs js -->
13 <script src="lib/ionic/js/ionic.bundle.js"></script>
14 <!-- cordova script (this will be a 404 during development) -->
15 <script src="cordova.js"></script>
16 <!-- your app's js -->
17 <script src="js/app.js"></script>
18 </head>
19 <body ng-app="starter" ng-controller="AppCtrl">
20 <ion-pane>
21 <ion-header-bar class="bar-stable">
22 <h1 class="title">Ionic Blank Starter</h1>
23 </ion-header-bar>
24
25 <ion-content padding="true">
26 <form ng-submit="submit()">
27 <label class="item item-input item-stacked-label">
28 <span class="input-label">Username</span>
29 <input type="text" name="username" placeholder="enter username"
30 ng-model="data.username">
31 </label>
32
33 <input class="button button-block button-positive" type="submit"
34 name="submit" value="Submit to server">
35 </form>
36
37 <div class="card">
38 <div class="item item-text-wrap">
39 Response: <b ng-bind="response"></b>
40 </div>
41 </div>
42 </ion-content>
43 </ion-pane>
</body>
</html>
Here you basically created a form with an username input field and
with a submitbutton. Using AngularJS ng-submit you’re saying that
once the submit button is clicked AngularJS should handle it within
the submit() function which you defined in app.js file before.
Input username uses the ng-model to bind to the variable on
the $scope so that you can then use it in your submit() function.
6. Run ionic serve from the root directory of your Ionic app (I’m sure
you know this, but just in case that’s where the folders
like www, plugins, scss reside).
Simple login example with Ionic and
AngularJS
DECEMBER 18, 2014 BY SIMON 108 COMMENTS
Many times you may want to have a login at the beginning of your app.
Handling a login with ionic and Angular is very straight forward. For the
purpose of this tutorial, I will use a simple starting template from the ionic
guys und just add a login before the template app shows.

Complete example: How To Handle User Authentication With


AngularJS Inside Your Ionic App

Setup the project


Go to your command line and start a new ionic app:

Start a new app

Shell

1 ionic start simple-login tabs


2 cd simple-login

3 ionic serve --lab

BTW: the –lab flag is quite new and shows how your app will look on ios &
Android. Epic stuff the guys at ionic are creating!

Modify our template


As we want to display our login page before the tabs you see right now, we
must add a new file in the www/templates folder, named login.html with
this content:

index.html

XHTML

1 <ion-view view-title="Login" name="login-view">

2 <ion-content class="padding">

3 <div class="list list-inset">

4 <label class="item item-input">

5 <input type="text" placeholder="Username" ng-model="data.username">

6 </label>

7 <label class="item item-input">

8 <input type="password" placeholder="Password" ng-model="data.password">

9 </label>

1 </div>

0
<button class="button button-block button-calm" ng-click="login()">Login</button>

1
</ion-content>
1

</ion-view>
1

1
3

So here we have a simple view, a small login form and a button. We will
assign everything needed in the controller later, for now lets add our route
so we can see our view the first time. Therefore, open up the app.js and
add this state to the already existing states:

Add a state

JavaScript

1 .state('login', {

2 url: '/login',

3 templateUrl: 'templates/login.html'

4 })

You can run your app now, and you should see a view like this:

If you want to make a login without credentials, also take a look at how to
support iOS TouchID in your app!

Get the Ionic Authentication Template


Enter your Email below to receive the Authentication app directly to
your inbox!
GET MY TEMPLATEPowered by ConvertKit

Adding the functions


BUT NOTHING WOKRS RIGHT NOW? Yeah, how shall things work
without a controller? So change our state to:

Another state

JavaScript

1 .state('login', {

2 url: '/login',

3 templateUrl: 'templates/login.html',

4 controller: 'LoginCtrl'

5 })

As mentioned from a comment (thanks to Matthias!), we have to set our


fallback route to /login, so that our login get’s called as first route. As
Matthias said, this is not the best way for production apps, but for now
include this below our states to make our app work:

Set a fallback state

JavaScript

1 $urlRouterProvider.otherwise('/login');

Now open up the controllers.js, and add our simple login controller:

LoginCtrl inside controllers.js

JavaScript

1 .controller('LoginCtrl', function($scope) {

2 $scope.data = {};

4 $scope.login = function() {

5 console.log("LOGIN user: " + $scope.data.username + " - PW: " + $scope.data.password);


6 }

7 })

Here we create our scope variable, which is connected to the form fields
we created in the login. The action is already connected to the login button,
so go ahead and try to login. For now this just logs the entered data. As you
often want to verify the data with a server, we will create a simple service to
verify the data. Open the services.js and add a new service:

LoginService inside services.js

JavaScript

1 .service('LoginService', function($q) {

2 return {

3 loginUser: function(name, pw) {

4 var deferred = $q.defer();

5 var promise = deferred.promise;

7 if (name == 'user' && pw == 'secret') {

8 deferred.resolve('Welcome ' + name + '!');

9 } else {

1 deferred.reject('Wrong credentials.');

0
}

1
promise.success = function(fn) {
1

promise.then(fn);
1

2 return promise;

1 }

3
promise.error = function(fn) {

1
4

1
promise.then(null, fn);
7
return promise;
1
}
8

return promise;
1

9
}

2
}
0
})
2

Ok this is a bit of code, but no magic. We create our loginService with


one function loginUser(), which expects the name and password of the
user. Obviously the whole promise construct is over the top for this simple
use-case but when you want to verify the user to a REST server, you need
to make it async. Therefore, it’s better to have it now already!

So in this case, we grant access to user/secret, and resolve our promise if


the credentials fit our expected user details. Otherwise, the promise gets
rejected.
The lines 12-18 are just a bit of syntactic sugar. I like the promise to have a

success/error function, otherwise we could just use .then(..) and check the

result, but with success and error the code is better to read in my opinion.

As result of our login function we return our promise, so now we must


include the service in our LoginCtrl. Change our controller to this:

Change the LoginCtrl

JavaScript

1 .controller('LoginCtrl', function($scope, LoginService, $ionicPopup, $state) {

2 $scope.data = {};

4 $scope.login = function() {

5 LoginService.loginUser($scope.data.username,

$scope.data.password).success(function(data) {
6

$state.go('tab.dash');
7

}).error(function(data) {
8

var alertPopup = $ionicPopup.alert({


9

title: 'Login failed!',


1

0 template: 'Please check your credentials!'

1 });

1
});

1
}
2

})
1

3
1

So here you can see how we use our service and promise correctly. First,
we need to add the LoginService dependency,
the $ionicPopup dependency for a simple popup and the $state for the
transition to the next view. The login function now calls the loginUser
function with the username and password entered in the form. Here we can
use the success() and error() function for handling the login. If the
credentials are as expected (user/secret), we navigate to the normal
starting point of the tabs template, tab.dash, using the $state. If the
credentials are wrong, we display a simple alert popup.

Now serve your app and try to login. EPIC! It just works

Interested in learning how to build apps with the Ionic Framework? Check
out my complete step-by-step video course Ionic by Doing!

So long,
Simon