{"id":1866,"date":"2015-06-19T07:52:36","date_gmt":"2015-06-19T07:52:36","guid":{"rendered":"http:\/\/www.nikola-breznjak.com\/blog\/?p=1866"},"modified":"2017-06-21T19:59:46","modified_gmt":"2017-06-21T19:59:46","slug":"posting-data-from-ionic-app-to-php-server","status":"publish","type":"post","link":"https:\/\/nikola-breznjak.com\/blog\/codeproject\/posting-data-from-ionic-app-to-php-server\/","title":{"rendered":"Posting data from Ionic app to PHP server"},"content":{"rendered":"<h3>TL;DR<\/h3>\n<p>This is the simplest example which shows how to POST&nbsp;data from an <a href=\"http:\/\/ionicframework.com\/\">Ionic<\/a> app to a PHP server.<\/p>\n<p>The tutorial covering the Ionic <a href=\"http:\/\/www.nikola-breznjak.com\/blog\/ionic2\/posting-data-from-ionic-2-app\/\">version 2 can be found here<\/a>.&nbsp;The tutorial covering the Ionic <a href=\"http:\/\/www.nikola-breznjak.com\/blog\/javascript\/ionic3\/posting-data-ionic-3-app-php-server\/\">version 3 can be found here<\/a>.<\/p>\n<h3>Quickstart<\/h3>\n<p>To see&nbsp;it in action:<\/p>\n<ol>\n<ol>\n<li><a href=\"https:\/\/github.com\/Hitman666\/IonicServerSave\">Clone the finished project<\/a> from Github<\/li>\n<li>Run <span class=\"lang:default decode:true crayon-inline \">ionic serve<\/span><\/li>\n<\/ol>\n<\/ol>\n<ol>\n<li>You should see something like this:<br \/>\n<a href=\"http:\/\/www.nikola-breznjak.com\/blog\/wp-content\/uploads\/2015\/06\/ionic_phpDemo.jpg\" rel=\"lightbox[1866]\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1871\" src=\"http:\/\/www.nikola-breznjak.com\/blog\/wp-content\/uploads\/2015\/06\/ionic_phpDemo.jpg\" alt=\"ionic_phpDemo\" width=\"411\" height=\"273\" srcset=\"https:\/\/nikola-breznjak.com\/blog\/wp-content\/uploads\/2015\/06\/ionic_phpDemo.jpg 411w, https:\/\/nikola-breznjak.com\/blog\/wp-content\/uploads\/2015\/06\/ionic_phpDemo-300x199.jpg 300w\" sizes=\"auto, (max-width: 411px) 100vw, 411px\" \/><\/a><\/li>\n<\/ol>\n<p>If you want to make it work&nbsp;from your server:<\/p>\n<ol>\n<li><a href=\"https:\/\/github.com\/Hitman666\/IonicServerSave\">Clone the finished project<\/a> from Github<\/li>\n<li>Upload the <strong>PHP\/api.php<\/strong> file to your server<\/li>\n<li>In the <strong>www\/js\/app.js<\/strong> file adjust the <strong>link<\/strong>&nbsp;variable to point to your server<\/li>\n<li>Run <span class=\"lang:default decode:true crayon-inline \">ionic serve<\/span><\/li>\n<\/ol>\n<h3>Step by step on how to create this yourself from scratch<\/h3>\n<ol>\n<li>Create a new blank Ionic project with:\n<pre class=\"lang:default decode:true\">ionic start ionicServerSendTest blank<\/pre>\n<\/li>\n<li>Copy the following code (you&#8217;ll already have the <strong>.run()<\/strong> part, the <strong>.controller()<\/strong> part is novelty here) in <strong>www\/js\/app.js<\/strong> file:\n<pre class=\"lang:default decode:true\">\/\/ Ionic Starter App\n\n\/\/ angular.module is a global place for creating, registering and retrieving Angular modules\n\/\/ 'starter' is the name of this angular module example (also set in a &lt;body&gt; attribute in index.html)\n\/\/ the 2nd parameter is an array of 'requires'\nangular.module('starter', ['ionic'])\n\n.run(function($ionicPlatform) {\n    $ionicPlatform.ready(function() {\n        \/\/ Hide the accessory bar by default (remove this to show the accessory bar above the keyboard\n        \/\/ for form inputs)\n        if (window.cordova &amp;&amp; window.cordova.plugins.Keyboard) {\n            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);\n        }\n        if (window.StatusBar) {\n            StatusBar.styleDefault();\n        }\n    });\n})\n\n.controller('AppCtrl', function($scope, $http) {\n    $scope.data = {};\n\n    $scope.submit = function(){\n        var link = 'http:\/\/nikola-breznjak.com\/_testings\/ionicPHP\/api.php';\n\n        $http.post(link, {username : $scope.data.username}).then(function (res){\n            $scope.response = res.data;\n        });\n    };\n});<\/pre>\n<\/li>\n<li>On your server, create a <strong>api.php<\/strong> file&nbsp;with the following content:\n<pre class=\"lang:default decode:true \">&lt;?php\n    \/\/http:\/\/stackoverflow.com\/questions\/18382740\/cors-not-working-php\n    if (isset($_SERVER['HTTP_ORIGIN'])) {\n        header(\"Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}\");\n        header('Access-Control-Allow-Credentials: true');\n        header('Access-Control-Max-Age: 86400');    \/\/ cache for 1 day\n    }\n\n    \/\/ Access-Control headers are received during OPTIONS requests\n    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {\n\n        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))\n            header(\"Access-Control-Allow-Methods: GET, POST, OPTIONS\");         \n\n        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))\n            header(\"Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}\");\n\n        exit(0);\n    }\n\n\n    \/\/http:\/\/stackoverflow.com\/questions\/15485354\/angular-http-post-to-php-and-undefined\n    $postdata = file_get_contents(\"php:\/\/input\");\n    if (isset($postdata)) {\n        $request = json_decode($postdata);\n        $username = $request-&gt;username;\n\n        if ($username != \"\") {\n            echo \"Server returns: \" . $username;\n        }\n        else {\n            echo \"Empty username parameter!\";\n        }\n    }\n    else {\n        echo \"Not called properly with username parameter!\";\n    }\n?&gt;<\/pre>\n<p>As you can see from the code, the first part is explained in detail in <a href=\"http:\/\/stackoverflow.com\/questions\/18382740\/cors-not-working-php\">this StackOverflow question<\/a>, and&nbsp;it basically solves the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTTP\/Access_control_CORS\">CORS<\/a> issue that you would otherwise run into.<\/p>\n<p>The second part, explained in detail in <a href=\"http:\/\/stackoverflow.com\/questions\/15485354\/angular-http-post-to-php-and-undefined\">this StackOverflow question<\/a>, &nbsp;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 <span class=\"lang:default decode:true crayon-inline \">json_decode<\/span>&nbsp; the data that comes to your PHP server.<\/li>\n<li>In <strong>www\/js\/app.js<\/strong> file adjust the <strong>link<\/strong>&nbsp;variable to point to&nbsp;the file on your server<\/li>\n<li>In <strong>www\/index.html<\/strong> file copy the following content:\n<pre class=\"lang:default decode:true \">&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n    &lt;head&gt;\n        &lt;meta charset=\"utf-8\"&gt;\n        &lt;meta name=\"viewport\" content=\"initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width\"&gt;\n        &lt;title&gt;&lt;\/title&gt;\n        &lt;link href=\"lib\/ionic\/css\/ionic.css\" rel=\"stylesheet\"&gt;\n        &lt;link href=\"css\/style.css\" rel=\"stylesheet\"&gt;\n        &lt;!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above\n        &lt;link href=\"css\/ionic.app.css\" rel=\"stylesheet\"&gt;\n        --&gt;\n        &lt;!-- ionic\/angularjs js --&gt;\n        &lt;script src=\"lib\/ionic\/js\/ionic.bundle.js\"&gt;&lt;\/script&gt;\n        &lt;!-- cordova script (this will be a 404 during development) --&gt;\n        &lt;script src=\"cordova.js\"&gt;&lt;\/script&gt;\n        &lt;!-- your app's js --&gt;\n        &lt;script src=\"js\/app.js\"&gt;&lt;\/script&gt;\n    &lt;\/head&gt;\n    &lt;body ng-app=\"starter\" ng-controller=\"AppCtrl\"&gt;\n        &lt;ion-pane&gt;\n            &lt;ion-header-bar class=\"bar-stable\"&gt;\n                &lt;h1 class=\"title\"&gt;Ionic Blank Starter&lt;\/h1&gt;\n            &lt;\/ion-header-bar&gt;\n\n            &lt;ion-content padding=\"true\"&gt;\n                &lt;form ng-submit=\"submit()\"&gt;\n                    &lt;label class=\"item item-input item-stacked-label\"&gt;\n                        &lt;span class=\"input-label\"&gt;Username&lt;\/span&gt;\n                        &lt;input type=\"text\" name=\"username\" placeholder=\"enter username\" ng-model=\"data.username\"&gt;\n                    &lt;\/label&gt;\n\n                    &lt;input class=\"button button-block button-positive\" type=\"submit\" name=\"submit\" value=\"Submit to server\"&gt;                    \n                &lt;\/form&gt;\n\n                &lt;div class=\"card\"&gt;\n                    &lt;div class=\"item item-text-wrap\"&gt;\n                        Response: &lt;b ng-bind=\"response\"&gt;&lt;\/b&gt;\n                    &lt;\/div&gt;\n                &lt;\/div&gt;\n            &lt;\/ion-content&gt;\n        &lt;\/ion-pane&gt;\n    &lt;\/body&gt;\n&lt;\/html&gt;<\/pre>\n<p>Here you basically created a form with an <strong>username<\/strong>&nbsp;input field and with a <strong>submit<\/strong> button. Using AngularJS <a href=\"https:\/\/docs.angularjs.org\/api\/ng\/directive\/ngSubmit\">ng-submit<\/a>&nbsp;you&#8217;re saying that once the submit button is clicked AngularJS should handle it within the <strong>submit()<\/strong> function which you defined in <strong>app.js<\/strong> file before. Input <strong>username<\/strong> uses&nbsp;&nbsp;the <strong>ng-model<\/strong> to bind to the variable on the <strong>$scope<\/strong> so that you can then use it in your <strong>submit()<\/strong> function.<\/li>\n<li>Run <span class=\"lang:default decode:true crayon-inline \">ionic serve<\/span>&nbsp; from the root directory of your Ionic app (<em>I&#8217;m sure you know this, but just in case that&#8217;s where the folders like <strong>www<\/strong>, <strong>plugins<\/strong>, <strong>scss<\/strong> reside<\/em>).<\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>TL;DR This is the simplest example which shows how to POST&nbsp;data from an Ionic app to a PHP server. The tutorial covering the Ionic version 2 can be&hellip;<\/p>\n","protected":false},"author":1,"featured_media":1867,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8,43],"tags":[],"class_list":["post-1866","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-codeproject","category-ionic"],"_links":{"self":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/1866","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/comments?post=1866"}],"version-history":[{"count":11,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/1866\/revisions"}],"predecessor-version":[{"id":3449,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/1866\/revisions\/3449"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/media\/1867"}],"wp:attachment":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/media?parent=1866"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/categories?post=1866"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/tags?post=1866"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}