{"id":3441,"date":"2017-06-21T19:47:56","date_gmt":"2017-06-21T19:47:56","guid":{"rendered":"http:\/\/www.nikola-breznjak.com\/blog\/?p=3441"},"modified":"2017-06-21T19:53:02","modified_gmt":"2017-06-21T19:53:02","slug":"posting-data-ionic-3-app-php-server","status":"publish","type":"post","link":"https:\/\/nikola-breznjak.com\/blog\/javascript\/ionic3\/posting-data-ionic-3-app-php-server\/","title":{"rendered":"Posting data from Ionic 3 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\/\">Ionic 3<\/a>&nbsp;app to a PHP server.<\/p>\n<p>The tutorial covering the Ionic <a href=\"http:\/\/www.nikola-breznjak.com\/blog\/codeproject\/posting-data-from-ionic-app-to-php-server\/\">version 1 can be found here<\/a>, and the tutorial covering the Ionic <a href=\"http:\/\/www.nikola-breznjak.com\/blog\/javascript\/ionic2\/posting-data-from-ionic-2-app\/\">version 2 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\/Ionic3ServerSendTest\">Clone the finished project<\/a> from Github<\/li>\n<li>Make sure you&#8217;ve got the newest Ionic 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\/2017\/06\/ionic3PostingToPHPserver.png\" rel=\"lightbox[3441]\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2521\" src=\"http:\/\/www.nikola-breznjak.com\/blog\/wp-content\/uploads\/2017\/06\/ionic3PostingToPHPserver.png\" alt=\"ionic2ServerPost\" width=\"358\" height=\"312\"><\/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 CLI (see below for instructions)<\/li>\n<li><a href=\"https:\/\/github.com\/Hitman666\/Ionic3ServerSendTest\">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>src\/pages\/home\/home.ts<\/strong>&nbsp;file adjust the <strong>link<\/strong>&nbsp;variable (line #21) 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 3<\/h3>\n<p>After neglecting Ionic 3 (and for the most part Ionic 2) for far too long due to the overburdening work I still have on my Ionic 1 apps, I finally got some time to take a look at Ionic 3 and update the most popular post about Ionic on my blog, so here you go and enjoy.<\/p>\n<blockquote><p><em>In general, from me playing just a bit with Ionic 3, I have to say I love it, so expect some more posts about it soon-ish&#8230;<\/em><\/p><\/blockquote>\n<p>To install the Ionic SDK and create Ionic 3 projects, you need to install the latest Ionic CLI:<\/p>\n<pre class=\"lang:default decode:true\">npm install -g ionic<\/pre>\n<blockquote><p>You don&#8217;t need to worry about this messing up your current ionic CLI since the new one still works with old Ionic 1 projects.<\/p><\/blockquote>\n<p>Just for reference, here&#8217;s what my <code>ionic info<\/code>&nbsp;says now:<\/p>\n<pre class=\"lang:default decode:true\">$&gt; ionic info \n\nglobal packages:\n\n    @ionic\/cli-utils : 1.4.0\n    Ionic CLI        : 3.4.0\n\nlocal packages:\n\n    @ionic\/app-scripts              : 1.3.7\n    @ionic\/cli-plugin-ionic-angular : 1.3.1\n    Ionic Framework                 : ionic-angular 3.4.2\n\nSystem:\n\n    Node       : v8.0.0\n    OS         : macOS Sierra\n    Xcode      : Xcode 8.3.3 Build version 8E3004b \n    ios-deploy : 1.9.1 \n    ios-sim    : 5.0.13 \n    npm        : 5.0.1 \n<\/pre>\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 Ionic3ServerSendTest blank<\/pre>\n<\/li>\n<li>Copy the following code to&nbsp;<strong>src\/pages\/home\/home.html<\/strong>&nbsp;file:\n<pre class=\"lang:default decode:true\">&lt;ion-header&gt;\n &lt;ion-navbar&gt;\n &lt;ion-title&gt;\n Ionic3 Server Send Test\n &lt;\/ion-title&gt;\n &lt;\/ion-navbar&gt;\n&lt;\/ion-header&gt;\n\n&lt;ion-content padding&gt;\n &lt;ion-list&gt;\n &lt;ion-item&gt;\n &lt;ion-label floating&gt;Username&lt;\/ion-label&gt;\n &lt;ion-input type=\"text\" name=\"username\" [(ngModel)]=\"data.username\"&gt;&lt;\/ion-input&gt;\n &lt;\/ion-item&gt;\n\n &lt;button ion-button 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>Once the button is clicked AngularJS should handle it within the <strong>submit()<\/strong> function which we will define in our&nbsp;<strong>src\/pages\/home\/home.ts<\/strong> file (shown below).<\/p>\n<p>Input <strong>username<\/strong> uses&nbsp;&nbsp;the new syntax for&nbsp;<strong>ng-model<\/strong>&nbsp;, 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>Components are a bit different in Ionic 3 now, so I encourage you can take a look at the <a href=\"http:\/\/ionicframework.com\/docs\/components\/#overview\">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>To the file&nbsp;<strong>src\/pages\/home\/home.ts<\/strong> file copy the following content and&nbsp;adjust the <strong>link<\/strong>&nbsp;variable to point to&nbsp;the file on your server:\n<pre class=\"lang:default decode:true\">import { Component } from '@angular\/core';\nimport { NavController } from 'ionic-angular';\nimport { Http } from '@angular\/http'; \/\/https:\/\/stackoverflow.com\/questions\/43609853\/angular-4-and-ionic-3-no-provider-for-http\n\n@Component({\n selector: 'page-home',\n templateUrl: 'home.html'\n})\n\nexport class HomePage {\n data:any = {};\n\n constructor(public navCtrl: NavController, public http: Http) {\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 myData = JSON.stringify({username: this.data.username});\n \n this.http.post(link, myData)\n .subscribe(data =&gt; {\n this.data.response = data[\"_body\"]; \/\/https:\/\/stackoverflow.com\/questions\/39574305\/property-body-does-not-exist-on-type-response\n }, error =&gt; {\n console.log(\"Oooops!\");\n });\n }\n}<\/pre>\n<p>As with the <a href=\"http:\/\/www.nikola-breznjak.com\/blog\/javascript\/ionic2\/posting-data-from-ionic-2-app\/\">Ionic 2 tutorial<\/a>, things have changed a lot since Ionic 1, but in Ionic 3 (if you come from Ionic 2) you shouldn&#8217;t have any problems. Anyways, practice makes perfect, so make sure you put in the hours of <a href=\"http:\/\/jamesclear.com\/deliberate-practice\">deliberate practice<\/a>.<\/p>\n<p>In this file, we<strong>&nbsp;<\/strong>import the<strong> Http<\/strong> component from Angular. You can check out the link in the comment to learn that you also need to import and inject&nbsp;<strong>HttpModule&nbsp;<\/strong>in&nbsp;<strong>src\/app\/app.module.ts&nbsp;<\/strong>(two new lines that I&#8217;ve added are bolded):<strong><br \/>\n<\/strong><\/p>\n<pre class=\"lang:default decode:true\">import { BrowserModule } from '@angular\/platform-browser';\nimport { ErrorHandler, NgModule } from '@angular\/core';\nimport { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';\nimport { SplashScreen } from '@ionic-native\/splash-screen';\nimport { StatusBar } from '@ionic-native\/status-bar';\n<strong>import { HttpModule} from '@angular\/http';<\/strong>\n\nimport { MyApp } from '.\/app.component';\nimport { HomePage } from '..\/pages\/home\/home';\n\n@NgModule({\n declarations: [\n MyApp,\n HomePage\n ],\n imports: [\n BrowserModule,\n IonicModule.forRoot(MyApp),\n <strong>HttpModule<\/strong>\n ],\n bootstrap: [IonicApp],\n entryComponents: [\n MyApp,\n HomePage\n ],\n providers: [\n StatusBar,\n SplashScreen,\n {provide: ErrorHandler, useClass: IonicErrorHandler}\n ]\n})\nexport class AppModule {}<\/pre>\n<p>Inside the <strong>HomePage<\/strong> 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.<\/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&nbsp;the&nbsp;<strong>subscribe<\/strong>&nbsp;function to handle data once it arrives. Also, make sure you check out the StackOverflow link in the comment as a solution of how to access plain text response.<\/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<\/ol>\n<p>That&#8217;s all folks, I hope this tutorial helps you in starting your journey towards Ionic3 &amp; Angular4!<\/p>\n<blockquote class=\"twitter-tweet\" data-width=\"550\">\n<p lang=\"en\" dir=\"ltr\">Posting data from <a href=\"https:\/\/twitter.com\/hashtag\/Ionic?src=hash\">#Ionic<\/a> 3 app to a <a href=\"https:\/\/twitter.com\/hashtag\/PHP?src=hash\">#PHP<\/a> server <a href=\"https:\/\/t.co\/QYKiQtq1kJ\">https:\/\/t.co\/QYKiQtq1kJ<\/a><\/p>\n<p>&mdash; Nikola Bre\u017enjak (@HitmanHR) <a href=\"https:\/\/twitter.com\/HitmanHR\/status\/877615082339012608\">June 21, 2017<\/a><\/p><\/blockquote>\n<p><script async src=\"\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script><\/p>\n","protected":false},"excerpt":{"rendered":"<p>TL;DR This is the simplest example which shows how to POST&nbsp;data from an Ionic 3&nbsp;app to a PHP server. The tutorial covering the Ionic version 1 can be&hellip;<\/p>\n","protected":false},"author":1,"featured_media":3444,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[56],"tags":[],"class_list":["post-3441","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ionic3"],"_links":{"self":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/3441","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=3441"}],"version-history":[{"count":4,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/3441\/revisions"}],"predecessor-version":[{"id":3447,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/3441\/revisions\/3447"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/media\/3444"}],"wp:attachment":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/media?parent=3441"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/categories?post=3441"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/tags?post=3441"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}