Posting Data From Ionic App To PHP Server
Posting Data From Ionic App To PHP Server
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:
<?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.
Shell
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!
index.html
XHTML
2 <ion-content class="padding">
6 </label>
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!
Another state
JavaScript
1 .state('login', {
2 url: '/login',
3 templateUrl: 'templates/login.html',
4 controller: 'LoginCtrl'
5 })
JavaScript
1 $urlRouterProvider.otherwise('/login');
Now open up the controllers.js, and add our simple login controller:
JavaScript
1 .controller('LoginCtrl', function($scope) {
2 $scope.data = {};
4 $scope.login = function() {
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:
JavaScript
1 .service('LoginService', function($q) {
2 return {
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
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.
JavaScript
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
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