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:
- Clone the finished project from Github
- Run ionic serve
If you want to make it work from your server:
- Clone the finished project from Github
- Upload the PHP/api.php file to your server
- In the www/js/app.js file adjust the link variable to point to your server
- Run ionic serve
Step by step on how to create this yourself from scratch
- Create a new blank Ionic project with:
ionic start ionicServerSendTest blank
- Copy the following code (you’ll already have the .run() part, the .controller() part is novelty here) in www/js/app.js file:
// 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; }); }; });
- On your server, create a api.php file with the following content:
<?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.
- In www/js/app.js file adjust the link variable to point to the file on your server
- In www/index.html file copy the following content:
<!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.
- 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).
Hello, thanks for this very useful post. What link should I use if I try to run this on localhost? And where to put the php.api file?
Hi Wade,
Thanks for your comment – I’m glad the post was useful to you!
So, if you are running this on localhost then the link would be something like http://127.0.0.1/api.php. Of course, in order for this to work, this file would have to be in the root folder of your localhost server. Let me explain a bit further – in case you’re using XAMP or WAMP then you have a www folder (in my case C:\wamp\www\), and you should put the api.php file there and it should be accessible from the link I provided. However, if you have some other folder yet inside the www folder (if, ofc, we’re talking about XAMP/WAMP, and if the folder is for example ionic) then the link you should use would be http://127.0.0.1/ionic/api.php.
Hope this helps to clarify. If you run into any other issues, just ping back…
Hi.. can I use http tunneling instead? like serveo.net
Haven’t tried, you?
hey Dude!! its awesome and the code i s too easy and good so thank you bro!!
Thanks man, I’m glad it was useful to you!
heyy..
I’m using ubuntu 14.04 Desktop..nd my ionic app is inside (Documents)
placed api.php in www folder of ionic app..but it gives error “POST http://localhost:8100/api.php———%5BHTTP/1.1 404 Not Found 1ms]” but by app.js is getting called “GET http://localhost:8100/js/app.js”
What to do?? 🙁
That’s because the api.php file has to be on your server and not locally in your Ionic application.
Hey, thanks fot this priceless tutorial.
I am getting a error and wonder if you could help!
XMLHttpRequest cannot load http://abc.com/api.php. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
I am very sure that i have followed the tutorial very minutely.
Hi, thank you, I’m glad you like it.
The http://abc.com/api.php is a placeholder (an example) link. You should put this file (api.php) on your own server and link to it appropriately.
For example, if you server’s domain is vishal.com and you place the api.php file in the root directory, then the link to it would be http://vishal.com/api.php.
If you need more help with this I can link you with some tutorials about servers and domains. Don’t be afraid to ask – if I know the answer, I’ll try to help.
when i test on browser, i use local file it errors 404 . How can i test it on browser ?
Hi ! thank you for this post it works perfectly fine 🙂 how is it going to be when you add more inputs or data?
nevermind my question :)) solved it myself. thanks 🙂
I’m glad you did 🙂
not working when installed on device what will be the problem
Can you please provide a bit more info? Do you get any error? How did you deploy to your phone? Did you put the script to your server? I hope you didn’t leave the abc.com/api.php 😉
When I run the app on my desktop browser using my ip address, it is able to insert the data into mysql. However, when i use ionic run android and installed the apk into my phone, I was not able to insert the data at all. Any idea what is going one?
Did you get any errors? Did you check the server logs for MySql errors? What do they say?
$http.post works perfectly on ionic serve > browser
But in the android apk it is not working at all
I included
And in my PHP file i included as per you have mentioned but still it is not working
Please suggest me.
Note: For example “http://mydevelopmentsite.com” i mentioned this
Thanks
Hi, sorry for the late reply. Your comment actually went to spam for some reason. Well, in order for me to help you I would have to have some more information like where did you put your api.php file? In case you put it locally on your computer then this just won’t work if you’ll test it on your mobile phone. In this case you have to put the api.php file to the real server which is accessible via it’s IP. Anyways, reply and we’ll see what we can come up with.
How to replace var link = ‘http://nikola-breznjak.com/_testings/ionicPHP/api.php’ with my server name?
I replied on CodeProject, and am pasting my reply here as well:
You just have to upload the api.php file to your server and replace the link with the actual link to this api.php file on your server.
For example, let’s say that your domain is superdomain.com and that you’ve put this api.php file in the root directory from which all your requests to HTTP are served (this tends to vary from server to server but it usually is something like /var/www/html. I repeat, usually, your system may be different). In that case the link should be replaced with: http://superdomain.com/api.php.
thanx a lottt …
No problem, glad to help!
Thanks for this tutorial!
What I appreciate most is that you explain what you are doing and even leave the link to where the problem / the question was discussed instead of presenting it as your own idea. That way interested readers have the chance to get more in detail!
Thanks a lot and best wishes,
Ahmed
Thank you for the kind words, I really appreciate it and I’m glad that my way of writing helps you.
Wish you all the best too!
That gives many answers!! Thanks Nikola !
You’re welcome Fatiha!
hi
its really working….but i want to generate its .apk file for android mobile then what is the next procedure.
You would have use the command: `ionic build` to build the .apk file which you could then deploy to your phone and test. For more details you can see the official documentation here: http://ionicframework.com/docs/guide/building.html.
thanks nikola great post
You’re welcome!
i want to fetch data from database in app from server,,my database located in online server ..then what is the procedure to fetch and display data….
Well, first you have to write the “program” which would fetch this data from the server. For example this can be a PHP script which then sits on the server and waits for requests from your Ionic app. It’s good if this “PHP script” would actually be a RESTful service. Please do some research on these terms and if you get stuck ping me and I’ll try to help…
on button click i want fetch data from database and display
ok…if u got any updates regarding plz contact me……
Yes, I actually have a tutorial planned on the subject of “How to write a RESTful service and consume it with Ionic”, and will ping you when it will be finished. Thanks for taking the time to comment!
Hi great tutorial!! but having some problems.. I set up and everything works fine pointing to your url http://nikola-breznjak.com/_testings/ionicPHP/api.php but when I switch to mine http://www.htgsolutions.com/icancha/api.php is not working, I double checked and everything seems to be fine, any idea? is there any additional configuration should I do on the php server? (BTW I’m using JustHost)
Thanks!
Hey Julio,
Thank you – I’m glad you like the post!
I just tried your link and indeed it’s not working. You used the same exact api.php file that I posted in the solution, right?
In that case I’m suspecting that it could be something with your web host. What I suggest is that you try the solutions mentioned in this StackOverflow thread: http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined and let me know if you managed to get some progress on the issue.
Good luck!
Dont forget ” WWW” before the adress. Exmple : var link = ‘http://www.domain.com/api.php’.
Thanks.
You’re welcome!
Hello there! Thank you very much for your post .
I followed to the letter and have my api.php on my server. with ionic serve the post reaches me perfectly, but when I run ionic android emulate not work for me . It also happens when I step apk in a real smartphone.
Can you think of something that reason?
Hi Guillermo,
I’m really glad you found the post useful.
The only thing that comes to my mind is that the internet connection on your phone would not be working? Could it be the case?
The connection is perfect .
The funny thing is that if I run ionic serve if it works, but if I run ionic emulate android then do not go .
It may be for the Android SDK versions ?
Hi ,
As you said, api is located on the server not in ionic app, so if i want to use api located in my app. How can i do ? Because when use link to api server same you , it is ok, but when i try to use local file , it errors 404 .
Thanks.
If I understand you correctly, what you’re looking for is a local database. Because, talking about local API is really something that doesn’t quite add up to what you’re trying to accomplish – it doesn’t make sense to “make API calls locally”. So, this “database” can be a simple file actually (as I see in your second question) to which you would write something and then read from it. I would suggest you take a look at http://learn.ionicframework.com/formulas/localstorage/. However, I have to stress out that if you think of calling api.php locally from your Ionic app – this just can’t work (it’s just not the way this is suppose to work). Because api.php file is a, well, PHP file which you have to run from some web server. I would also suggest you take a look at this: http://blog.mashape.com/list-of-40-tutorials-on-how-to-create-an-api/
Hi Nikola.
Awesome post!!!… But I have a problem:
I use your code to create a login page, when I run it on localhost, or with: “iconic serve –lab” everything works great, in fact I customice your code and I can send e-mails to users if the login was succesfull or show a modal page if an error hapends.
The problem is when I send it to phonegap to generate the pkg and install it on a device, everything works great until “$http.post(link, …”.
In fact I thought the problema was my code so I download your script from github and just modify the api.php to my domain. In this case we got the same problem, everything works perfect with localhost or with “iconic serve –lab” but no when create the pkg with phonegap.
Can you tell me where is the problem? Did you try to generate your script with phonegap and run it?
Thank you so much
Hi Agustin,
I’m glad my post helped you!
Why are you using phonegap? Ionic has a simple `ionic build android` command which then creates the needed .apk file (for Android).
Hello Nikola
Thanks for you soon reply.
I´m using phonegap because it generate the App in iOS, Android and Windows. I´m going to try to generate the App as you told me and I´ll tell you how it will be.
Thanks for the code you have posted, it’s very helpful for me, can you please help me that how to create an post method to get response from server in Angularjs using ionic framework..
You can see in the following code that that’s exactly what we do:
$http.post(link, {username : $scope.data.username}).then(function (res){
$scope.response = res.data;
});
So, we send a post to the server, and then in the success callback function we take this response and assign it to a $scope.response variable.
Hope this helps clear the confustion.
Hey I tested this using my azure server I didn’t change a thing except the link and I won’t give me a response. When I try using your site the response works perfectly fine. Is there anything to do with azure I need to change or do?
Hmm, just to be certain (since I’m not familiar with Azure) – you did set it up to be able to run PHP, right?
Hi Nikola,
is there any way to secure connection/data between mobile app and server?
If user look in source code, he can see where is POST script (in your example that is api.php) and he can make same POST from other source than mobile app.
So, how to receive data only from mobile app, and block other POST sources?
Data is not sensitive, so there is no need for https.
Hi Antonio,
From my experience there’s just no viable (longterm) solution to fix this. For example, you could opt in to send a certain hash and then check this hash on the server. But, again, someone can look at your source and find that you’re using this hash. So, that option is not quite viable. You could use minimization and obfuscation, but again someone may listen for the traffic and see the requests which are coming in (I’m not an expert on this, but I asked a friend and he confirmed that anything can be tracked these days) and then repeat them with any automated script.
You can take a look at this SO answer for more info: http://stackoverflow.com/questions/32533064/how-to-restrict-api-endpoint-access-to-certain-clients
Hope this helps a bit.
Hi Nikola. Thank you for this. I am having the same problem that a couple of other people are having regarding my app. I’m using ionic, and it runs perfectly when i run “ionic serve”. I get a response back and it works exactly like its suppose to. However, when I run in on my android device or emulator, it doesn’t return a value when I click “submit”. Is there something I need to change in my ionic config file or something?
Any help would be great! Thanks again.
Ryan
Hey Ryan,
Thanks, I’m glad you found the tutorial useful. Can you please confirm that this thing happens if you download my project from Github and deploy it to the device?
Hi Nikola. I figure out what happened and hopefully this will help someone else. I didn’t create a “blank” project. I basically added your code into an existing project. Once I followed your steps exactly, I was able to get it to work.
I’m not sure why it wasn’t working outside of my browser when I added the code to an existing project, but it definitely wasn’t. No matter what I did. Creating the blank project and following the steps above, exactly, worked.
Thanks you for your time!
Ryan
Hey Ryan,
Thanks, I’m glad you got it working now!
Good luck on your projects!
Which ide did you used for developing this login module??
Thanks for your question – I’m using Sublime Text 3, which actually isn’t an IDE, but a text editor.
Hello Nikola
Thank you very much for your post .
I have also storing username into database.
I have my api.php on my server. with ionic serve everything is perfect [Storing data, posting data], but when I build for android apk and installing apk on android phone, it doesnt work for me.
Not getting any error or any kind of response from server.
Pls reply asap.
Thank You.
It may be due to the whitelisting. Take a look at this plugin: http://docs.ionic.io/docs/cordova-whitelist. And also, you may need InApp browser: https://github.com/apache/cordova-plugin-inappbrowser.
Hope this gets you going in some direction…
Thank You So Much.
It works fine for me….
Great, I’m glad it worked! Good luck with your project!
Hi Nikola. Thank you for this. I want to try and modify the code to make it work with two input fields (like username and password) but I didn’t found the solution, i’m not an expert in JS and may be I don’t understand all your code. How should I proceed ?
Thanks and sorry for my bad english !
Please don’t take this the wrong way, but to be honest. Like, really honest – I would invest some time in learning JavaScript first. And PHP if that’s your language of choice for the backend. Because, even if I show you how to do this task now (which is really a minor thing) you won’t learn anything. If you do try something for yourself, post the code which you’ve tried on StackOverflow and tell which part exactly is “not working”, so that that way we can help.
Hi Nikola. Thanks for your reply. With some time in learning I’ve succeeded at doing what I wanted. I wonder if your solution is a good way to do communicate an Ionic app with a database (like postgre) ?
No probs – please don’t forget to mark the answer as accepted on SO. Yes, I don’t see why not. Basically, what you do is you create a REST API endpoint and then you consume it from your Ionic app via Angular.
Hi
Your solution works when i am running on the Browser. But when i create the apk and install it on the phone than it did not send request to server.
Please let me know how can i solve that issue.
I would be best if you could run it on your device via `ionic run android –device android -lcs` and set up logs all over the code so that you could see if you get any errors. Hope this helps a bit…
Hi Nikola,
Thanks for sharing this tutorial.
I have implemented your codes into my ionic project, I have a php file on my server which I added its link into your code.
I build the apk via ‘ionic build android’ command in my terminal and installed it onto my device.
When I enter the username it returns ‘Empty username parameter!’ error message.
It seems like the $username data is empty, even though I enter it onto the html form.
My controller is ‘LoginCtrl’ because I would like to further edit your code to create a login form. I tried by changing to ‘AppCtrl’ but that would disable any links in my project.
I don’t understand why it keeps on returning ‘Empty username parameter!’ in the app.
Can you please help me with this issue.
Thanks in advanced:)
Hi Omaz,
If you could create a Codepen example with your code I could take a look.
Thanks for this. The code is working well on browser but after compiling to .apk, the button does not work again. What could be the problem.
Note: I changed the link to my server link, created new table and uploaded the new file but it would’t work
What do your logs on the server say, do you receive the request? What does the console in your browser say after you click on the initiated ajax request?
There is nothing showing on the log about the activity
Hi when i m using your link then its working fine…
but when i link our server then nothing happens………
pls solve this problem…
Did you put the same PHP file to your server? Is your server at all configured to execute PHP files?
Himanshu Rawat,i have same problem with you. if i run on my android ,it cannot connect to myserver. what is the problem nikola ? thanks for attention
Do you have the InAppBrowser plugin installed? Though, more you would also see if you take a look at the server logs and figure out if the requests are coming through to your server.
my server address is http://copperjam.in/postdata.php
but not data retrieve when we use your link its working plz tell me step by step process what happen
code in postdata is
username;
if ($username != “”) {
echo “Server returns: ” . $username;
}
else {
echo “Empty username parameter!”;
}
}
else {
echo “Not called properly with username parameter!”;
}
?>
in my server log
[23-Apr-2016 04:56:59 UTC] PHP Notice: Trying to get property of non-object in /public_html/copperjam/postdata.php on line 27
plz solve this problem
And, what do you conclude from the server logs?
The PHP code that you have in postdata.php is not the same as I wrote it in the tutorial.
It seems you’re lacking the basic knowledge of PHP, so I would kindly recommend you read some basic tutorials about it.
Good luck!
sorry couldn’t paste complete code
here is complete
username;
if ($username != “”) {
echo “Server returns: ” . $username;
}
else {
echo “Empty username parameter!”;
}
}
else {
echo “Not called properly with username parameter!”;
}
?>
my code is same as u but here i think “->” error
username;
if ($username != “”) {
echo “Server returns: ” . $username;
}
else {
echo “Empty username parameter!”;
}
}
else {
echo “Not called properly with username parameter!”;
}
?>
It seems you’re starting with PHP, so I would recommend that you first invest some decent amount of time into learning it properly.
give me ur email id then i’ll mail u my php file
in here comment section code couldn’t paste complete code.
Sir now I know more about php . plz solve my issue. its imp for now .and i am stuck here .
Hi. Nice post!
How do you organize the services on php server for ionic?
For example. Do you create one file for each one method? Or.. Do you send a parameter for you choice de method in a once file api.php?
And about of security of the transfers informations… Its safe?
Thanks!
Hi Gustavo,
Thank you, I’m glad the post was useful to you!
I prefer to have a single file which lists the methods, but then separate files for actual function implementations. But, honestly, either way (even with multiple files) it will be fine until you stick to this and not do it a bit like this and then a bit like that. Take one approach that seems logical to you and stick to it.
As for the security, it seems that JWT are hot topic these days: https://jwt.io/.
Thanks, Nikola!!!
app.controller(‘vilvamCtrl’,function($scope, $http){
$scope.submit = function(){
$http.post(‘/login.php’,{username:$scope.username, password:$scope.password})
.then(function(response){
$scope.response = response.data;
})
}
});
that was my controller. I am not getting where i went wrong. I placed the php file in the app folder along with scss, www, etc.
Can u help me with this.
You can’t just place login.php in the app folder. You need to place it on your server that actually “understands” and can interpret PHP code.
tried that too ‘localhost/login.php’.
And do you have a server running at your local machine? I mean, sorry I don’t want to be rude, but it seems you’re really a beginner at this so please read some more about how actually PHP works and where you should put your PHP files.
Sry for the trouble i am new to php and angularjs. thank you for your help, i got it working. you post is really helpful. thanks
No problem, I’m glad you solved it! Remember, don’t give up when you hit a roadblock. And, by solving it yourself, you’ve probably learned more than when someone just ‘tells you the solution’. Good luck going forward!
hi, JAGADEESH, how did you solve this problem?
Hello,
Thanks for the nice tutorial. I appreciate. I am having some issues getting checkbox values from ionic form and posting to php. I have series of check boxes that need to be posted based on selection. Please guide me on the best way to pass those values as well. Thanks in advance.
Here is my checkbox Makeup:
{{quote.text}}
Please create a jsFiddle (or similar) with your code snippet.
how can send data from php to ionic?
If I understand you correctly, then one way is by using sockets. However, traditionally you would use REST where the client (Ionic app) fetches something from the server (PHP app).
thank’s a lot NIKOLA, actually in my php admin panel , admin want to send content to (ionic app), how can do this ? i don’t know really how can i do this ?
Well, you don’t. Seems like you’re really just starting with this so I would recommend that you read a bit about REST (http://code.tutsplus.com/tutorials/a-beginners-guide-to-http-and-rest–net-16340). The thing is, you can’t do it the way you’re asking/thinking it. You have to write a PHP script that will then act as a ‘provider of your data’. Data, which you will then ‘consume/fetch/get’ in your Ionic app via Angular’s $http service.
Hola, Muchas gracias.
Excelente contenido y muy buena explicación.
De nada.
i have a project it works correctly on the localmachine
when i uploaded the php file and database on the server it did not work idont know why ?
this is the link
can you please have a look and tell me why it did not work
thanks
Sorry, but I don’t open up rar’s. Please post your code in pastebin or some other online service. And, what do the logs say?
Very nice tutorial, but I’m having the same problem as others have. Everything works fine in a browser but when I do ‘ionic upload” the button just doesn’t work anymore.
If I change the link to your link, then it works on the device but not in the browser (console output:
ionic.bundle.js:25000 Mixed Content: The page at ‘https://www.exampledomain.com/app/index.html#/menu/register’ was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint ‘http://nikola-breznjak.com/_testings/ionicPHP/api.php’. This request has been blocked; the content must be served over HTTPS.
But when I use my link (it is an https link) it works in the browser but not on the ios device.
My thought is that it has something todo with the difference in http and https link? Do you have any ideas about this?
Thanks in advance
Ok so the problem was that my ssl certificate wasn’t installed correctly. Installed it again and it worked! I also added “SSLProtocol all -SSLv3 -SSLv2” to the “ssl.conf” file, so no more Poodle attacks. I just mention this because it maybe has something to do with security reasons of why it didn’t work before. Below the steps of how I did it:
Step 1. sudo nano /etc/apache2/mods-available/ssl.conf
Step 2. change line “SSLProtocol all” into “SSLProtocol all -SSLv3 -SSLv2”
Thanks for your update!
Hi there, I am developing an Ionic app and using your tutorial. After having tried to learn from plenty of tutorials yours seems to best out there ! And seeing as your answering comments,
Was hoping you could provide me some help ? I have a few pesky questions 😛
1) In the CORS part, is that where I would also add headers to confirm http versions and content types ? [Or is that only for when you send commands to the server from a shell ?}
2) How would I go about handling POST, GET, PUT.. ? With a switch statement?
3) For user sign-ins would I need to do something special with password handling? Could I access the sent data with $_post and $_get ?
4) Could you quickly explain how the data is sent from Ionic to server? Is it the same as sending a web form from a website?
Sorry if I’m not making sense, made a c# server and client that worked through shell, also made a simple php-sql server website to display/update/get data. I am studying computer science so I should probably be understanding this 😛
Also I don’t know how to display the sending/receiving of data on the URL bar, is there some specific way of doing it? Only ever made the messages (eg. HTTP/1.1 200 OK Content-type: text/plain “data” ) for consoles.
Thanks in advance for your help.
1) Uff, I honestly don’t know what you mean here.
2) Yes, you could do it like that.
3) Yes, you can access the sent data with $_POST. As for password handling, only thing is that you save your passwords in the database in a non-plaintext way. There are a lot of tuts out there for that part in case you’ll be looking more into it.
4) Yes, exact same thing. It’s sent as an AJAX request (most likely a POST request)
The question about sending/receiving of data in the URL bar – that I don’t quite understand. But, when you make your program in like say PHP, then you have to put on some server which has Apache or Nginx running so that it can run your PHP code.
All in all, don’t be discourage if things don’t fall into place the very first time you go through it. Just keep pushing and I’m sure you’ll get it all.
Thanks for the fast answer 🙂 Yeah I have been wasting 2 months on back-end research 😛 Slowed down my app so much :/
And when I made a PHP website some time ago it all seemed so much easier 😛 I am trying to go with a MongoDB solution, so that brings in more hassle as it is completely new to me. I can’t even understand how to test or set-up the environment (MongoDB [ Heard I can use WAMP or smthg with it])
Basically I made a C# client/server that were console programs. They just generated HTTP posts/gets and server responses for all http protocols. But no graphic display.
The PHP project I did had a bad front end UI 😛 But I dont think you could call it a REST api 😛 It just did some minor sql conecting and retrieving of data.
If you know where I can find more information on making a API with MongoDB/PHP for Ionic I will welcome the link. And if you know a good tutorial to set up a MongoDB/php-server I would welcome that too 🙂
Also I don’t see in your api.php page how you send back the response to the Ionic platform. I assume the echo would only display that information on the .php page
You’re welcome.
Erm, no, you can’t use WAMP with MongoDB at all. MongoDB is totally different from that. With WAMP you would have MySQL database. If you want, you can go over this tutorial series that I wrote for Pluralsight on MEAN stack, and it covers MongoDB in detail: https://hackhands.com/how-to-get-started-on-the-mean-stack/. I also have a free/(pay as you want) book about it (https://leanpub.com/meantodo).
Well, if you did that with C# already, the concept is absolutelly not different. Because, you must have had some server you were sending requests to .
I would actually challenge your choice of MongoDB and PHP, as I would guess that the most common solution is PHP + MySQL. But, not that it’s not possible. It’s totally fine if you choose to go that way. I did a quick google search and it seems there are tutorials on this combination (PHP + MongoDB).
So, here’s the thing; since you mentioned UI and REST in same sentence, that indicates that you need to brush up a bit on that research. Namely, you want to make your (REST) API respond with only data. And god forbid if you try to return some html inside it :). In general, you send a request from your app to the service api and you get back some data (most likely in json format) which you then (manipulate and) show in the app.
> Also I don’t see in your api.php page how you send back the response to the Ionic platform. I assume the echo would only display that information on the .php page
No, on the contrary, that’s exactly how I ‘return’ something via PHP to the app that’s calling this API. Simple echo.
Thanks for clearing that all up 😀
In my first php project I did return HTML tables and other stuff from my php code 😛
That’s not a problem. I did it the same way back when I was starting. The only thing is; now that you know how it should be done, you need to strive towards learning and applying this stuff 🙂
🙂 The PHP and MongoDB choice is because I heard nosql is the way forward as it is scalable, fast deploying and flexible as a DB. I know SQL server but due to the time it takes to make robust data model and supposed downtimes in the future if there are major changes I opted to try something new. The PHP choice is because its the only language I have worked with on the backend really. I have not really looked at the asp/.Net MVC. I have done some basic networking with C# but that is it. Also just trying to broaden my horizon in terms of technologies. I guess I am a “mixed” Full stack developer 😛 Not sure if thats a good choice. Anyway I will probably stop spamming your comment section. Thanks again for all your help.!!!
No problemo, glad to help. In general, if you’re going with MongoDB you’ll see that often people choose Node.js alongside it. Which again leads us to the ever so slightly popular MEAN stack. Good luck!
sir, how would i know that my api.php is working or not? because index.html will always give me the response..
I have some last annoying question 😛 I promise it will be the last, you see your the only one that seems to want to share some answers 😛
hmm, so I have some web space that support PHP and MySQL. However not mongodb. Is there a way to leave the php on the web server and have a local mongoDB connecting to the server?
If not:
You said WAMP and MongoDB would not work? What would I use to develop locally ? I do not have a PHP environment on my own PC.
I would still, at the end of the day, recommend you go with PHP + MySQL :). But, since you persist :), the easiest way to use mongo (which you can have locally – well, not in an easy to explain way) and access it via PHP that you have on your server is to try: https://mlab.com/ or https://www.compose.com/. The first one gives you 500MB for free, which will be way more than you need for your testing. That way you can kickstart your mongo foo without having to manage the mongoDB locally or install it on some other server.
If, however, you’re feeling ambitious, I would suggest you get a digital ocean account (here’s a link to get 10$ for free https://m.do.co/c/974c9bc93d77 – that will last you for two months!) and spin up a server with MongoDB already installed (or you can go crazy and install a fresh linux ‘droplet’ and install MongoDB on it from scratch :). You can install also a PHP on another droplet (it’s just a name how they call their VPSes), or well on the same one if you like. Ah, the vast number of options…
Thank you again haha 😀 Awesome tutorials and great advice !
Hi, I’ve built an ionic front-end project and now I’m moving on to backend. I need to connect my ionic app to a existing web hosting mysql database. There is already a website built on this database, I need to let my app and the website share the same database. However the server that the web hosting company uses does not have any API for Ionic apps. Is your way of connecting database applicable to my situation? Thank you a lot for your help.
Hope this answers your question: http://stackoverflow.com/documentation/ionic-framework/4003/connecting-ionic-with-any-database#t=201608180539450196224. TL;DR: write an API and put it on this server that you have (if I’m not mistaking you’re using PHP, and there’s no problem to do it with that).
Hello, me again! Thank you for your reply.
I’m trying to test your code on the server but failed. I’ve uploaded the api.php to the server and changed link but I got no server response. I’m not sure whether I uploaded correctly or not. As here I cannot upload screenshot, is it possible for me to consult you through email? Thank you for you time.
If you’ve put your file to a domain like example.com in the root folder – does visiting http://example.com/api.php give you any output? If not, take a look at your web server logs and output here what they say.
Yes it gives me output “Empty username parameter!”. But no response when I do ionic serve.
And what does console log in your browser tell you (after you run with ionic serve and click the submit button)?
This one: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Do you have any solution to this. Thank you a lot! You are so patient and helpful 🙂
I use this Chrome plugin to solve that: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
For other solutions just google for “No ‘Access-Control-Allow-Origin’ header is present”
It’s working now with the plugin. Thank you very much! 🙂
Glad to help!
Hi,
Thanks a lot for such a nice post. It helped me a lot.
The only problem i m facing now is it is returning “Empty username parameter!” .
test.php
table;
if ($username != “”) {
echo “Server returns: ” . $username;
}
else {
echo “Empty username parameter!”;
}
}
else {
echo “Not called properly with username parameter!”;
}
?>
———————-
contoler.js
$scope.username = “abc”;
$http.post(“http://mydomain.com/test.php”, {username : $scope.username},{headers: {‘Content-Type’: ‘application/x-www-form-urlencoded;’}}).then(function (res){
console.log(res);
alert(“yes”);
},function(err){
alert(“error”);
});
——————————-
please help me out.
Try logging the `$scope.username` variable before you do the $http.post so that you can verify that you are trying to send something. Also, on the PHP side, try do var_dump the variables that should come in and see what the logs say.
tried $scope.username option i m sending value to php.
in fact its working on localhost and also on 127.0.0.1 so i think its not the problem of CROS
is there any chance of server setting (hosting provider)
Hello Mr. Nikola, and thank u for this useful tuto, but i have a problem, when i start the ionic serve , all works fine and i got server response: admin (admin is the username), but in the api.php i got Empty username parameter! , any idea ?
If I understood you correctly – you get the “admin” word back. Which only means you do get back from the server what you’ve sent. So I really don’t know what do you mean by the empty username parameter and where were you checking this.
it works thank you
And what was the issue?
Hello Nikola, Thank u for this. but i want to store data in server site and how to fetch it.
You’re welcome. And, what have you tried so far?
Hey there again Nikola,
Its me again I am back 😛
Now that I am further in my application I have come to the part where I am curious to know how I can encrypt or protect the body of my put/post requests from Ionic to my PHP API (Slim). I heard something about using https ? Is there an other way ? And how would I potentially go about implementing it in Ionic and in the API.
Hi Vic,
Welcome back 🙂
Yes, add https and you’ll be fine. Don’t add https and you’ll come up with all sorts of crazy things like encrypting the post variables and stuff like that (and then decrypting them on the backend).
Thanks, this must be a popular page !
Oh ok that sounds simple 🙂 By addind HTTPS you mean getting a HTTPS server only? Would I have to specify HTTPS from Ionic ? Is there an Ionic HTTPS ($http.post.. ) equivalent (such as $https.post..) ?
Indeed it is 😉
So, you need to get an SSL certificate for your domain. Research this a bit and if you get stuck you know where to come ;). You will most likely buy this and set on your domain provider (but again, your mileage may vary). Nope, everything stays the same from Ionic, you’ll only do $http.post(‘https://yourcoolsite.com/app.php’…. Hope this gives you enough to work on for now.
Yep should keep me busy another few weeks or months 😀 See you soon ! xD Thanks again
Yep should keep me busy another few weeks or months 😀 See you soon ! xD Thanks again
hi there. First of all i want to thank you for this tutorial and i used this and post and get data from my server. But i have an issue, when i tested on browser “ionic serve –lab” it’s working perfect. But when i tested in my device “ionic run android -l -c” there is an error when i made usb debugging “‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://192.168.2.169:8100’ is therefore not allowed access.” i put my api.php on my server and i linked correctly. But as i said i get this error when i tested in my android device. Can you help me about this issue?
Thanks, I’m glad it was helpful to you. Check if this helps you: https://www.thepolyglotdeveloper.com/2015/05/whitelist-external-resources-for-use-in-ionic-framework/
thanks for the reply. i resolved my issue.
It would be helpful for others if you outlined how.
i get data from my website in json format. and i have mobile version of my website which auto redirect when visit with mobile devices to mobile version. so i tried the desktop version of api link. example http://www.mysite.com/api.php. but device is mobile and auto redirect to mobile version and try to get data from http://www.mysite.com/m/api.php. so i changed my links in my app then i can get all datas correctly. this is my solution of my issue.
Thanks.
hi, this is a very useful tutorial, you can also show me the process for getting data from the server into my ionic app?
Thank’s
You can do it similarly, by using $http.get() service: https://docs.angularjs.org/api/ng/service/$http
hi there, is there a way to get data from ng-value. I try to use inputs with ng-value because i must bind data for update but i get errors. How can i get ng-value in to my controller for posting to php server?
See if this helps: https://docs.angularjs.org/api/ng/directive/ngValue
Thank you for your post. Its working but the value can’t store the database.
please help me to connect database on ionic
Please take a look at this, hope it helps: http://stackoverflow.com/documentation/ionic-framework/4003/connecting-ionic-with-any-database#t=201610252019377773701.
How to recover this error
ionic.bundle.js:26799 Error: [ng:areq] Argument ‘AppCtrl’ is not a function, got undefined
Try if this helps: http://stackoverflow.com/questions/23983143/argument-appctrl-is-not-a-function-got-undefined-http-angular-ionic-error
Hai Nikola,
I have an error “Cross-Origin Request Blocked”. Please help me to solve this error.
Thank you.
Hi Ricky,
Sure, can you please tell me what have you tried so far to resolve the issue and where it was going wrong? I, for example, use CORS plugin for Chrome to resolve this.
Hi Nikola,
How to Create an SMS Notification In Ionic Frame Work
Hi MUGUNDARAMANUJAM,
What have you tried so far? Where did you bump into a roadblock?
hi, it works for me and i’m able to retreive an array from the file api.php, my question is how can i print array’s elements in the options of a select?
NIKOLA BREŽNJAK Sir…, i want to fetch username as well as password for this app how can i do that…How to add password field for this app…so that the database can return both username and password in response.
Hi Nikola, I found this tutorial interesting but I’m new in ionic and have the same issue.
In my case I want to get data from a webserver that respond with XMLHttpRequest (a .net webservice) and I have no access to this server to put api.php there. I can only call webservice methods and get some data from it. I don’t know what can I do at client side to solve CORS problem. I think that possibly I could not understand the solution exactly. Is it correct? or there is an other way for me?
Thanks in advanced
Hi Reza,
Well, in that case you could try with a plugin like this: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi.
The thing is, you could try to run your code in an emulator, or on a real device even and you’ll notice that most likely you won’t even have this issue there.
Do let me know if this gets you any further in your attempts to get this working.
Good luck!
Thank you for your attention. I have added this plugin to my chrome browser but unfortunately this issue still. What I should be done yet?
Regards
Hi Nikola again. Actually I’ve added this plugin but there are differences between enabled or disabled state in browser. when the property is disable, the response is “XmlHttpRequest can not load …. No access control-allow-origin ….” but when the property is enable, a HTML page were loaded and there is an error in the page as follows ” The test form is only available for requests from the local machine.”
Please tell are a meaningful difference there?
Thanks a lot
When the plugin is enabled it’s doing what’s it supposed to do – enabling CORS. You need that for when you’re testing in your browser. However, please make sure you turn it off for when you’re watching Youtube of surfing Facebook, as it will prevent those sites from working. Come to think of it, that may not be a bad ideas at all 😉
Hello there,
Nothing happens when i click on the submit button. Please help.
What do the logs tell you?
I’m getting OPTIONS net::ERR_EMPTY_RESPONSE error showing up on console logs. I followed all the steps but I can’t manage it to work. I placed the api.php on a free web hosting for testing: http://democratic-flanges.000webhostapp.com/ionic/api.php, please help.
Seems like it was a web hosting problem, script is running fine now.
I’m glad it worked!
Hi Nikola..thanks for this awesome tutorial..helped me a lot. 🙂
Is there any other way to deal with CORS error without writing that “Access-Control-Allow-Origin” code in php??
Hey, thank you, I’m glad it did! Well, you could the CORS Chrome plugin and see if that will help. Let me know if that solely will do the trick. The plugin link: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi.
Hi Nikola.
Firstly, I want to say you have created a great blog.
I have two question but the first one is about angularjs. I had a data base that It was working without any error, but two days ago It broke and I can not display the data in the browser, the mistake that show the browser is “ngRepeat:dupes” Athought I have tried to use the track by+ expression It does not work. Do you know how I can resolve the error? If you want to see the error I am sending you the domain.
Thanks un advance
thank u for great tutorial .
I am need to connect ionic with mysql database to validate the username and password with already stored username and password
Great tutorial. Thanks.
For people with the problem that isn’t working from the apk you must add whitelist and inappbrowser.
i cant post my data.. empty values are going to server..
Hello, this site are very cool !!
But I have a problem, when I try to call my website I have a error (Notice: Trying to get property of non-object in …/api.php on line 26) the line 26 are this line: $username = $request->username;
Thanks,
Lucien B.L.
This means that nothing came to your server. Please check if you’re sending the correct values over.
Do you know how to retrieve(select) from mysql using ionic 1 or do you have post it already?
Yes, I already wrote about this here: http://stackoverflow.com/documentation/ionic-framework/4003/connecting-ionic-with-any-database#t=20170425185352634478. Please see if that helps.
Good Work Sir, I have been trying to connect this to mysqli but can’t get this to work, please what should i do?
api.php
first_name;
$last_name=$request->last_name;
$gender=$request->gender;
$email=$request->email;
$phone_no=$request->phone_no;
$dob=$request->dob;
$password=$request->password;
$password=crypt($password);
$conn = new mysqli(“localhost”, “root”, “”, “original”);
// To protect MySQL injection for Security purpose
$first_name = stripslashes($first_name);
$last_name = stripslashes($last_name);
$email = stripslashes($email);
$phone_no = stripslashes($phone_no);
$dob = stripslashes($dob);
$gender = stripslashes($gender);
$password = stripslashes($password);
$first_name = $conn->real_escape_string($first_name);
$last_name = $conn->real_escape_string($last_name);
$email = $conn->real_escape_string($email);
$phone_no = $conn->real_escape_string($phone_no);
$dob = $conn->real_escape_string($dob);
$gender = $conn->real_escape_string($gender);
$password = $conn->real_escape_string($password);
$check=”SELECT count(*) FROM users WHERE id = ‘$email'”;
$rs = mysqli_query($conn,$check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 0) {
$outp='{“result”:{“created”: “0” , “exists”: “1” } }’;
}
else{
$sql = “INSERT INTO users VALUES (‘$first_name’, ‘$last_name’, ‘$email’, ‘$phone_no’, ‘$dob’, ‘$gender’, ‘password’ )”;
if ($conn->query($sql) === TRUE) {
$outp='{“result”:{“created”: “1”, “exists”: “0” } }’;
}
}
echo $outp;
$conn->close();
}
//okay here is my code
?>
Controller.js
.controller(‘signupCtrl’, function($scope,$http,$ionicPopup,$state,$ionicHistory) {
$scope.signup=function(data){
var link = ‘http://localhost/php/api.php’;
$http.post(link, {first_name: data.first_name, last_name : data.last_name, gender:data.gender, email : data.email , phone_no: data.phone_no , dob : data.dob, password : data.password})
.then(function (res){
$scope.response = res.data.result;
if($scope.response.created==”1″){
$scope.title=”Account Created!”;
$scope.template=”Your account has been successfully created!”;
//no back option
$ionicHistory.nextViewOptions({
disableAnimate: true,
disableBack: true
});
$state.go(‘login’, {}, {location: “replace”, reload: true});
}else if($scope.response.exists==”1″){
$scope.title=”Email Already exists”;
$scope.template=”Please click forgot password if necessary”;
}else{
$scope.title=”Failed”;
$scope.template=”Contact Our Technical Team”;
}
var alertPopup = $ionicPopup.alert({
title: $scope.title,
template: $scope.template
});
});
}
})
Hey Sammy, what error are you getting?
Hi Brother , Thank you soo much for this awesome article.
i have little problem how i can setup my server ?? i am building ionic app as an my semester project i am worried how i’ll setup my server and all that because i dont have much knowledge about this . please guide
Thanks
You’re welcome, I’m glad it was useful to you!
Since that example is in PHP I’d suggest you check out few tutorials about PHP. But, truth be told, it seems no one these days seem to like PHP although it even runs on a majority of sites… Anyways, get some hosting that will let you execute PHP code and train… Locally you can use something like XAMPP if you’re on Windows. Good luck!
Hello ! thank you for this post ? but how is it going to be when you add more inputs or data? Please
I’m glad you found it useful. Have you tried adding more? What was the problem you encountered? Do you have example code you used, so I can help you better?
It’s a syntax problem from myself i think x)
$http.post(link, {username : $scope.data.username}).then(function (res){….
I try ta add “Nickename” like this
$http.post(link, {username : $scope.data.username; nickname: $scope.data.nickname}).then(function (res){
But no working.
Sorry to solicite you for something like that but i’m a begginer 😀
Yeah, so, this should be written like:
{username : $scope.data.username, nickname: $scope.data.nickname}
So, comma (,) instead of ;
Of course, you should also update the code on the backend to handle the ‘nickname’.
If you’re a beginner then I’d suggest reading a bit upon JSON format and JavaScript objects.
Good luck!
Ahahahah, thank you for your time and your post.
Those little things that are born the biggest problem x)
Have a nice day !
Thanks, you too!
Hello Sir, This actually worked well but how can i use this method to send image and save it in a mysql db, Or if i can send mail via this method with file attachment.
Thanks for sharing. its really working,
thank you so much…. you wrote really a nice, precise and self explanatory code. you saved me a lot of time. i wish i could donate you something in return.
Donations are always welcome 😉
Good day Sir, Please how can i pass image from the ionic app and send it to the php script…Please help me
Hey Kasim, I think that the post from my friend Simon will help: https://devdactic.com/ionic-image-upload-nodejs-server/
Great post!
Everything working, except for one error on the PHP side:
Failed to load … : No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8100’ is therefore not allowed access.
Thank you Anna! Please see other comments about this if they help? Basically, installing a chrome CORS plugin may help.
sir i am getting this..any way to resolve this? thank you
“Notice: Trying to get property of non-object in C:\xamp”p\htdocs\api.php on line 40”
Could you post your api.php? Did you use the exact one I provided in the example on Github?
Hello NIKOLA BREŽNJAK,
Can you please guide me how can I secure / encrypt the data which is being posted from ionic to server using #http.post() because anyone can tamper it on the way.
I have already setup SSL on my server as well, but still data is not secure which travel between client-server using services.
Thanks
Hey Sunil, this will help you: https://stackoverflow.com/questions/1008668/how-secure-is-a-http-post. TL;DR, if you added SSL, you should be fine.
Buen tutorial…me ayudó en mi proyecto ionic. Gracias
Gracias!
Hi Nik, Thanks for your article. i`ve been searching for simplest method to learn ionic #LoL.,
since i found this awesome article..
now, i add some parameters on php also on app.js, and ofcourse on form. everything works like charms 🙂
my question is, how to upload image in same form?
thank you Nik.
Hey, thanks – my friend Simon has a good tutorial on that topic: https://devdactic.com/ionic-2-images/