{"id":2501,"date":"2016-01-19T13:35:45","date_gmt":"2016-01-19T13:35:45","guid":{"rendered":"http:\/\/www.nikola-breznjak.com\/blog\/?p=2501"},"modified":"2017-06-21T20:00:08","modified_gmt":"2017-06-21T20:00:08","slug":"posting-data-from-ionic-2-app","status":"publish","type":"post","link":"https:\/\/nikola-breznjak.com\/blog\/javascript\/ionic2\/posting-data-from-ionic-2-app\/","title":{"rendered":"Posting data from Ionic 2 app to a 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\/docs\/v2\/\">Ionic&nbsp;2<\/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\/Ionic2ServerSendTest\">Clone the finished project<\/a> from Github<\/li>\n<li>Make sure you&#8217;ve got the newest Ionic beta CLI (see below for instructions)<\/li>\n<li>Run <span class=\"lang:default decode:true crayon-inline\">ionic serve<\/span><\/li>\n<li>You should see something like this:<br \/>\n<a href=\"http:\/\/www.nikola-breznjak.com\/blog\/wp-content\/uploads\/2016\/01\/ionic2ServerPost.jpg\" rel=\"lightbox[2501]\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2521\" src=\"http:\/\/www.nikola-breznjak.com\/blog\/wp-content\/uploads\/2016\/01\/ionic2ServerPost.jpg\" alt=\"ionic2ServerPost\" width=\"358\" height=\"312\" srcset=\"https:\/\/nikola-breznjak.com\/blog\/wp-content\/uploads\/2016\/01\/ionic2ServerPost.jpg 358w, https:\/\/nikola-breznjak.com\/blog\/wp-content\/uploads\/2016\/01\/ionic2ServerPost-300x261.jpg 300w\" sizes=\"auto, (max-width: 358px) 100vw, 358px\" \/><\/a><\/li>\n<\/ol>\n<\/ol>\n<p>If you want to make it work&nbsp;from your server:<\/p>\n<ol>\n<li>Make sure you&#8217;ve got the newest Ionic beta CLI (see below for instructions)<\/li>\n<li><a href=\"https:\/\/github.com\/Hitman666\/Ionic2ServerSendTest\">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>app\/pages\/home\/home.js<\/strong>&nbsp;file adjust the <strong>link<\/strong>&nbsp;variable (line #18) 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>Getting started with Ionic 2<\/h3>\n<p>By now you probably have heard that Ionic is in beta for its <a href=\"http:\/\/ionicframework.com\/docs\/v2\/\">version 2<\/a>, which closely follows <a href=\"https:\/\/angular.io\/\">Angular 2<\/a>.<\/p>\n<blockquote><p><strong>You can find a lot more Ionic 2 related tutorials on my friend&nbsp;<a href=\"http:\/\/www.gajotres.net\/\">Gajotres<\/a>&nbsp;site.<\/strong><\/p><\/blockquote>\n<p>To install the Ionic SDK and create Ionic 2 projects, you need to install the latest beta release:<\/p>\n<pre class=\"lang:default decode:true \">npm install -g ionic@beta<\/pre>\n<blockquote><p>You don&#8217;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.<\/p><\/blockquote>\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 Ionic2ServerSendTest blank --v2<\/pre>\n<\/li>\n<li>Copy the following code in <strong>app\/pages\/home\/home.html<\/strong>&nbsp;file:\n<pre class=\"lang:default decode:true\">&lt;ion-navbar *navbar&gt;\n    &lt;ion-title&gt;\n        Home\n    &lt;\/ion-title&gt;\n&lt;\/ion-navbar&gt;\n\n&lt;ion-content padding&gt;\n    &lt;ion-list&gt;\n        &lt;ion-input floating-label&gt;\n            &lt;ion-label&gt;Username&lt;\/ion-label&gt;\n            &lt;input type=\"text\" name=\"username\" [(ngModel)]=\"data.username\"&gt;\n        &lt;\/ion-input&gt;\n\n        &lt;button round block (click)=\"submit()\"&gt;Submit to server&lt;\/button&gt;\n    &lt;\/ion-list&gt;\n\n    &lt;ion-card&gt;\n        &lt;ion-card-header&gt;\n            Response\n        &lt;\/ion-card-header&gt;\n        \n        &lt;ion-card-content&gt;\n            &lt;b&gt;{{data.response}}&lt;\/b&gt;\n        &lt;\/ion-card-content&gt;\n    &lt;\/ion-card&gt;\n&lt;\/ion-content&gt;\n<\/pre>\n<p>Here you basically created a form with an <strong>username<\/strong>&nbsp;input field and with a button which acts as a&nbsp;<strong>submit<\/strong> button.<\/p>\n<p>As you can see, the syntax is a bit different since Ionic2 uses <a href=\"https:\/\/angular.io\/\">Angular2<\/a>. Once the button is clicked AngularJS should handle it within the <strong>submit()<\/strong> function which we will define in our&nbsp;<strong>app\/pages\/home\/home.js<\/strong> file (shown below).<\/p>\n<p>Input <strong>username<\/strong> uses&nbsp;&nbsp;the new syntax for&nbsp;<strong>ng-model<\/strong>&nbsp;as well, and it binds to the variable <strong>data.username<\/strong>, so that you can then use it in your <strong>submit()<\/strong> function (shown below).<\/p>\n<p>Also, components are a bit different in Ionic now, and I encourage you can take a look at the <a href=\"http:\/\/ionicframework.com\/docs\/v2\/components\/\">official documentation<\/a>.<\/li>\n<li>On your server, create an&nbsp;<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 to your PHP server. The gist is that since we POSTed in a JSON format, we 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>app\/pages\/home\/home.js<\/strong>&nbsp;file adjust the <strong>link<\/strong>&nbsp;variable to point to&nbsp;the file on your server<\/li>\n<li>In <strong>app\/pages\/home\/home.js<\/strong> file copy the following content:\n<pre class=\"lang:default decode:true\">import {Page} from 'ionic\/ionic';\nimport {Http} from 'angular2\/http';\n\n@Page({\n    templateUrl: 'build\/pages\/home\/home.html',\n})\n\nexport class HomePage {\n    constructor(http: Http) {\n        this.data = {};\n        this.data.username = '';\n        this.data.response = '';\n\n        this.http = http;\n    }\n\n    submit() {\n        var link = 'http:\/\/nikola-breznjak.com\/_testings\/ionicPHP\/api.php';\n        var data = JSON.stringify({username: this.data.username});\n        \n        this.http.post(link, data)\n        .subscribe(data =&gt; {\n            this.data.response = data._body;\n        }, error =&gt; {\n            console.log(\"Oooops!\");\n        });\n  }\n}<\/pre>\n<p>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&#8217;t). But, that will change with usage, so no worries.<\/p>\n<p>First thing that we do here is we import <strong>Page<\/strong> and <strong>Http<\/strong> components from Ionic and Angular, respectively. Then we&#8217;re setting the Page <strong>templateUrl<\/strong> to our <strong>home.html<\/strong> file.<\/p>\n<p>Inside the HomePage class we now have a constructor where we&#8217;re setting some default values. Important to note, see how we&#8217;re passing in <strong>Http&nbsp;<\/strong>via the constructor parameter. Again, I won&#8217;t go into details of using this, as I mentioned you can take a look at a lot more in depth tutorials on <a href=\"http:\/\/www.gajotres.net\/\">Gajotres<\/a>.<\/p>\n<p>Inside the <strong>submit<\/strong> function we use the http service to post to our API endpoint with some data. Make note of how we use <strong>subscribe<\/strong> to handle data once it &nbsp;arrives.<\/li>\n<li>Run <span class=\"lang:default decode:true crayon-inline\">ionic serve<\/span>&nbsp; from the root directory of your Ionic app<\/li>\n<li>Hope this tutorial helps you in starting your journey towards (Ionic + Angular)_2<\/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&nbsp;2 app to a PHP server. The tutorial covering the Ionic version 2 can be&hellip;<\/p>\n","protected":false},"author":1,"featured_media":2508,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[49],"tags":[],"class_list":["post-2501","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ionic2"],"_links":{"self":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/2501","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=2501"}],"version-history":[{"count":4,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/2501\/revisions"}],"predecessor-version":[{"id":3450,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/2501\/revisions\/3450"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/media\/2508"}],"wp:attachment":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/media?parent=2501"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/categories?post=2501"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/tags?post=2501"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}