Click here to Skip to main content
15,888,121 members
Articles / Programming Languages / PHP

Posting Data from Ionic App to PHP Server

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
29 Jun 2015CPOL2 min read 97.9K   3   13
This is the simplest example which shows how to POST data from an Ionic app to a PHP server.

TL;DR

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

Quickstart

To see it in action:

  1. Clone the finished project from Github
  2. Run
    ionic serve
  3. You should see something like this:

    ionic_phpDemo

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:
    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:
    PHP
    // Ionic Starter App
    
    // angular.module is a global place for creating, registering and retrieving Angular modules
    // 'starter' is the name of this angular module example 
    // (also set in a <body> attribute in index.html)
    // the 2nd parameter is an array of 'requires'
    angular.module('starter', ['ionic'])
    
    .run(function($ionicPlatform) {
        $ionicPlatform.ready(function() {
            // Hide the accessory bar by default 
            // (remove this to show the accessory bar above the keyboard
            // for form inputs)
            if (window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            }
            if (window.StatusBar) {
                StatusBar.styleDefault();
            }
        });
    })
    
    .controller('AppCtrl', function($scope, $http) {
        $scope.data = {};
    
        $scope.submit = function(){
            var link = 'http://nikola-breznjak.com/_testings/ionicPHP/api.php';
    
            $http.post(link, {username : $scope.data.username}).then(function (res){
                $scope.response = res.data;
            });
        };
    });
  3. On your server, create a api.php file with the following content:
    PHP
    <?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 (basically an AngularJS app) to your PHP server. The gist is that AngularJS POSTs by default in a JSON format, and thus you have to

    json_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:
    HTML
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="initial-scale=1, 
            maximum-scale=1, user-scalable=no, width=device-width">
            <title></title>
            <link href="lib/ionic/css/ionic.css" rel="stylesheet">
            <link href="css/style.css" rel="stylesheet">
            <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
            <link href="css/ionic.app.css" rel="stylesheet">
            -->
            <!-- ionic/angularjs js -->
            <script src="lib/ionic/js/ionic.bundle.js"></script>
            <!-- cordova script (this will be a 404 during development) -->
            <script src="cordova.js"></script>
            <!-- your app's js -->
            <script src="js/app.js"></script>
        </head>
        <body ng-app="starter" ng-controller="AppCtrl">
            <ion-pane>
                <ion-header-bar class="bar-stable">
                    <h1 class="title">Ionic Blank Starter</h1>
                </ion-header-bar>
    
                <ion-content padding="true">
                    <form ng-submit="submit()">
                        <label class="item item-input item-stacked-label">
                            <span class="input-label">Username</span>
                            <input type="text" name="username" 
                            placeholder="enter username" ng-model="data.username">
                        </label>
    
                        <input class="button button-block button-positive" 
                        type="submit" name="submit" value="Submit to server">                    
                    </form>
    
                    <div class="card">
                        <div class="item item-text-wrap">
                            Response: <b ng-bind="response"></b>
                        </div>
                    </div>
                </ion-content>
            </ion-pane>
        </body>
    </html>

    Here, you basically created a form with an username input field and with a submit button. 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).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Croatia Croatia
I’m an engineer at heart and a jack of all trades kind of guy.

For those who care about titles, I hold a masters degree in computing from FER (and a black belt in karate, but that’s another story…).

During the last years, worked in a betting software industry where I made use of my knowledge in areas ranging from full-stack (web & desktop) development to game development through Linux and database administration and use of various languages (C#, PHP, JavaScript to name just a few).

Currently, I’m a senior software engineer at TelTech, where we make innovative communications apps, and I <3 it.

Lately, I’m very passionate about Ionic framework and am currently in the top 3 answerers on StackOverflow in Ionic framework. I wrote a book about Ionic framework which you can get for free on Leanpub: Ionic framework – step by step from idea through prototyping to the app stores.

Other technical writing:

+ wrote a book Getting MEAN with MEMEs
was a technical reviewer for a book Deploying Node published by Packt
was a technical reviewer for a book Getting started with Ionic published by Packt
After writing 300 posts, this is why I think you should start blogging too

Come and see what I write about on my blog.

Comments and Discussions

 
Questioncors issue Pin
Member 1399916226-Sep-18 20:06
Member 1399916226-Sep-18 20:06 
Questionwork with localhost? Pin
Member 1279376714-Oct-16 4:29
Member 1279376714-Oct-16 4:29 
QuestionCan't make a post with ionic app Pin
mingoia23-Sep-16 4:58
mingoia23-Sep-16 4:58 
AnswerRe: Can't make a post with ionic app Pin
Nikola Breznjak23-Sep-16 5:45
professionalNikola Breznjak23-Sep-16 5:45 
QuestionIonic framework Pin
Member 1228137522-Jan-16 7:07
Member 1228137522-Jan-16 7:07 
QuestionWhy does it not work as an APK? Pin
Member 122412873-Jan-16 4:13
Member 122412873-Jan-16 4:13 
AnswerRe: Why does it not work as an APK? Pin
Member 122412873-Jan-16 5:51
Member 122412873-Jan-16 5:51 
GeneralRe: Why does it not work as an APK? Pin
Nikola Breznjak3-Jan-16 7:04
professionalNikola Breznjak3-Jan-16 7:04 
GeneralRe: Why does it not work as an APK? Pin
Member 122412873-Jan-16 8:47
Member 122412873-Jan-16 8:47 
QuestionHow to use my server? Pin
Member 1215201518-Nov-15 22:00
Member 1215201518-Nov-15 22:00 
AnswerRe: How to use my server? Pin
Nikola Breznjak18-Nov-15 22:14
professionalNikola Breznjak18-Nov-15 22:14 
QuestionSecurity Pin
Lorenzo Calabrò9-Nov-15 22:27
Lorenzo Calabrò9-Nov-15 22:27 
AnswerRe: Security Pin
Nikola Breznjak9-Nov-15 23:39
professionalNikola Breznjak9-Nov-15 23:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.