Make HTTP Requests In Android And iOS With IonicFramework

As a modern developer, at some point in time you’re going to find yourself needing to work with a RESTful API.  You’re going to need to make HTTP requests to get data into your app or even change data on a remote database.

Lucky for us, making HTTP requests with IonicFramework is a heck of a lot easier than making them with native code.

The following will show you how to make GET requests for JSON data at some fictional API endpoint.  It is for Ionic Framework 1.  If you’re looking for how to make HTTP requests using Ionic 2, check here.

In AngularJS you can use the $http service to make requests.  The following is an example of how to use the $http service:

Lucky for us, we can use the same code in our Ionic project.

So lets go ahead and create a new Ionic project with the Android and iOS platforms:

Just note that if you’re not on a Mac, you cannot add the iOS platform.  Let’s go ahead and crack open the www/js/app.js file and create a new controller for our project:

When you call the getData() method from your HTML file it will make a GET request to our fictional RESTful endpoint passing a few parameters.  If successful, we are expecting the data response to have a firstname and lastname element which we will store in our scope.

Some things to note when making HTTP requests with IonicFramework or any JavaScript framework for that matter.  You may run into issues with cross origin resource sharing (CORS) errors.  There shouldn’t be an issue when testing your requests from the device, only from a browser.  To resolve these browser errors, check out a previous article I made on the subject.

A video version of this article can be seen below.

Nic Raboy

Nic is a skilled application developer who has released several native and hybrid mobile applications to iTunes and Google Play. He writes about his development experiences related to making web and mobile app development easier to understand and has experience in Android, Node.js, Apache Cordova, Java, NoSQL, SQL, GoLang, NativeScript, and Unity3D.

  • Jon

    Hey Nic,
    My q is on displaying an iframe that is in the data. My Javascript is weak, so I’m struggling with trying to display the iframe. For example let’s say in my json list is this.
    {
    id:2,
    name: ‘Nehalem Bay Salmon’ ,
    address: ‘OR’,
    url: ‘http://somethingmapbox.com/3874837/’
    }

    In my index.html page has a button that I’m trying to display the iframe of url, not the string ‘http://…’
    Hope you understand what I mean.

    • Hi Jon,

      I could be wrong, but I thought I saw somewhere that iFrames have some issues with mobile apps. If you’re feeling adventurous, maybe you can try the following:

      iframe ng-src="{{data.url}}" width="100%"

      Of course you need to add the url to your $scope first. ng-src will allow you to use AngularJS brackets.

      For the best possible mobile experience you should probably not try to render what is on the web. What you find on the web is heavy and slow. Maybe create your own UI based on the response data you receive instead.

      Cheers,

  • cby

    Good morning,

    im tried to follow your tutorial and it is great way to learn, but when i tried it on my own in my xampp local server i got no json data displayed.
    i noticed that when my json format is like this [{“name”:”Steve”,”state”:”CA”}] i got no data displayed

    but when my json format is like this one {“name”:”Steve”,”state”:”CA”} the data is being displayed

    here is my controller
    .controller(‘TestController’, function($scope, $http){
    $http.get(‘http://192.168.10.33/api/data’).then(function(resp){
    console.log(‘Success’, resp);
    $scope.name = resp.data.name;
    }, function (err){
    console.error(‘ERR’,err);
    })
    })

    here is my html part
    name: {{name}}

    • In the first scenario you created a JSON array of objects. This means you would need to do something like this:

      The second scenario worked because it was no longer an array.

      Hopefully that makes sense.

      Regards,

      • cby

        @nicraboy:disqus i tried $scope.name = resp.data[0].name; and i was able to display the name,
        but when i already had JSON like this {“details”: [{“name”:”Steve”,”state”:”CA”}, {“name”:”Jeo”,”state”:”CA”}]}
        and used $scope.name = resp.data.details[0].name;

        and want to display all the name it only display 1 name

        • I suggest you look into ng-repeat.

          You’re working with arrays so defining an index such as 0 will only print one record. You need to loop through the array.

          Regards,

      • cby

        i use this instead to show all JSON data, is this correct? or any easy way to do this?

        .controller(‘TestController’, function($scope, $http){

  • Mike

    How would you do this if you needed a username and password for the get request?

    • Like mentioned in the example, you’d pass them as parameters:

      I wouldn’t use a GET request for that. You’d probably want to use a POST on an endpoint that uses an HTTPS / SSL connection for security.

      This is all assuming the provider requires username / password as parameters and not in a header. Your question is too vague for me to answer all the way through.

      Regards,

  • Jordan

    Hey Guys, if you’re app works on web browser but doesn’t work on emulator that’s cause
    Cordova released cordova-android 4.0 with the laster version of the cordova cli.
    The changes in cordova-android prevent any http request by default.

    To fix this, all you have to do is add the cordova-whitelist-plugin.

    ionic plugin add cordova-plugin-whitelist

    Found this fix over at the ionic forum, cheers!

    http://forum.ionicframework.com/t/http-get-errors-with-android/23420

    • Thanks!

    • FX Bayu Anggara

      Thanks Jordan, I have a headache to facing it. It’s all solved when I’ve added the plugin 🙂 .. regards

  • Jasguerrero

    I got a question, I want to consume this json {“data”:{“id”:”1″,”title”:”Eum velit.”,”description”: “Description”}} but I don’t know how to display. For your attention thanks

    • I suggest you read up on some AngularJS, but typically you would assign the response to a $scope variable. Maybe something like this:

      Where responseData is your JSON string.

      Then in your HTML file you would do something like:

      Again, this is just a rough idea. Definitely do some research.

      Regards,

  • sirMuffles

    Great post! Is there any way to preload the data while the app is starting to avoid the awkward blank screen before the content is fetched?

  • Jomel Barbadillo

    I’m having trouble connecting to localhost. can someone help me to fix this. im newbie btw.

    kindly, see the picture below

    • What is the error? Without seeing the error it is impossible to help you.

      Regards,

      • Jomel Barbadillo

        when i’ll click the send button. i’ll get this.
        i’ll try to use adb logcat to see errors. and im like ughh. whats wrong?

        • That screenshot does nothing for me. You need to have the actual error message print out in your logs so ADB can pick it up. An alert doesn’t tell anything more than something went wrong. We need to know what went wrong.

          Regards,

          • Jomel Barbadillo

            i use console.log() but i can’t see errors

          • Jomel Barbadillo

            i can’t see the errors because of this:
            Exec() call to unknown plugin: Console
            i try to remove console plugin and install it again. but i always get that error

          • Jomel Barbadillo

            in genymotion browser i access my php file. but when i click sa the send button i get this error. the requested URL was not found on this server.
            im using this “http://10.0.3.2/dummy/connecting.php” as my url.

          • Calling it in a browser is a GET request. Are you sure you’re doing a GET request in AngularJS?

            Regards,

          • Jomel Barbadillo

            i really don’t know.

          • Jomel Barbadillo

            sorry. sir i really don’t know what to say. i’m stack on this almost 3weeks. can you give me other tips.

          • I think my final suggestions to you are as follows:

            Stop testing locally. Host your PHP site on a remote server. Your test approach is not working
            Read more on the AngularJS $http commands
            Make sure your PHP API is correct

            You’re wasting way too much time on this. Either your PHP code is not correct or your app code is having trouble communicating due to being local.

            That is as much as I can offer you.

            Best of luck,

          • Jomel Barbadillo

            I spend a weeks of doing it locally and i have to do your suggestions immediately. Thank you sir for your kindness.

          • Jomel Barbadillo

            Thank you sir!

          • Jomel Barbadillo

            The Genymotion IP address: 10.0.3.15 . I do believe I’m almost there hahaha I’m not giving up.

  • Le Zuero

    I’m having trouble with the following code:

    $http.get(“http://gpodder.net/search.json”, {params: {“q”:”mises”}}).success(function(data){ })

    In the browser it is OK, but in the device, not work at all.

    • What do your device logs say?

      • Le Zuero

        I solved my issue. I installed cordova white list and now $http.ge t is working on device. Thanks.

  • shahril

    Hello Nic, can you teach me about $http.post .. For example, I have a single form at mobile application which are using ionic framework and user should be fill in their information in particular form at mobile application . After that, the data will be send to external server (mysql database). Not into sqlite mobile. I already try with my own code but the result is failed. At console I got error ” OPTIONS https://localhost/pokok_apps/kdma/insert.php net::ERR_CONNECTION_REFUSED” . So, do you have a tutorial or some research about it ? because I need it.

    • You cannot access localhost from your device or simulator. This is why you’re getting ERR_CONNECTION_REFUSED. Figure out the correct IP or set up hosting with a domain name.

      Regards,

      • shahril

        Hi Nic, I got other issue that I dont know how to fix it .. You can refer from this link
        http://forum.ionicframework.com/t/how-to-save-data-from-external-server-json-into-sqlite-database-in-ionic-framework/29823
        I hope you can help.

        thanks in advance.

        • If you want help from me in my blog, you’re going to have to post your question in the comments, not link me to a third party resource.

          Regards,

          • shahril

            owh…i’m so sorry..ok .. the situation like this..
            I need to save the data from JSON format into SQLite mobile database. JSON data come from web service which are from external server. This is some example JSON data I create :

            [{“id”:”6″,”fullname”:”sadad”,”ic_no”:”12313″,”private_phone”:”2221″,”office_phone”:”4443″,”position”:”fff”,”email”:”[email protected]”,”password”:”12345″}]

            This is my controller.js

            .controller(‘AppCtrl’, function($scope,$ionicPlatform,$location,$http,$ionicHistory, $cordovaSQLite) {
            $ionicHistory.nextViewOptions({
            disableAnimate:true,
            disableBack:true
            });
            $ionicPlatform.ready(function(){
            $scope.loginData = {};
            $scope.sync = [];
            $scope.doLogin =function(){
            if(window.Connection) {
            //no connection to internet no sync process happen
            if(navigator.connection.type == Connection.NONE) {
            $location.path(‘/app/playlists’);
            }
            //connection available sync process will execute
            else{
            $http.get(‘http://ip-server/pokok_apps/kdma/fetch.php’, {params:{“ic_no”: $scope.loginData.ic_no,”password”: $scope.loginData.password}})
            .success(function(data){
            $scope.li = data;
            var query = “INSERT INTO user_kdma (id,fullname,ic_no,private_phone,office_phone,position,email,password) VALUES (?,?,?,?,?,?,?,?)”;
            $cordovaSQLite.execute(db, query, [$scope.li.id,$scope.li.fullname,$scope.li.ic_no,$scope.li.private_phone,$scope.li.office_phone,$scope.li.position,$scope.li.email,$scope.li.password]).then(function(res) {
            $scope.sync.push({id: $scope.li.id,fullname: $scope.li.fullname,ic_no: $scope.li.ic_no,private_phone: $scope.li.private_phone,office_phone: $scope.li.office_phone,position: $scope.li.position,email: $scope.li.email,password: $scope.li.password});
            console.log(data);
            }, function (err) {
            console.error(err);
            });
            //$location.path(‘/app/browse’);
            })
            .error(function(data){
            alert(‘error’);
            });

            )}

            {params:{“ic_no”: $scope.loginData.ic_no,”password”: $scope.loginData.password}}. loginData.ic_no come from what user enter at another page and the url will be like this http://ip-server/pokok_apps/kdma/fetch.php?ic_no=123&password=12345

            This is my php code at web service

            This is my adb logcat

            V/sqlg ( 5396): prepare db 0x7fca821f8b88 sql BEGIN
            V/sqlg ( 5396): sqlc_st_finish 0x7fca82302148
            V/sqlg ( 5396): prepare db 0x7fca821f8b88 sql INSERT INTO user_kdma (id,fullname,ic_no,private_phone,office_phone,position,email,password) VALUES (?,?,?,?,?,?,?,?)
            V/sqlg ( 5396): sqlc_st_finish 0x7fca82302288
            V/sqlg ( 5396): prepare db 0x7fca821f8b88 sql COMMIT
            D/SystemWebChromeClient( 5396): file:///android_asset/www/plugins/cordova-plugin-console/www/console-via-logger.js: Line 173 : [object Object]
            I/chromium( 5396): [INFO:CONSOLE(173)] “[object Object]”, source: file:///android_asset/www/plugins/cordova-plugin-console/www/console-via-logger.js (173)
            V/sqlg ( 5396): sqlc_st_finish 0x7fca82302288

            Actually no error found at adb logcat except “[object Object]”. What thats mean ? And its look like the SQL query executed but no data inserted into SQLite database. This picture from adb shell . I think request to the web service are correct because I try to display the data at index.html using method ng-repeat=’list in li’ , {{list.fullname}} and the data display at index.html. So, where the problem come from ? how to fix it ? Is it from $scope.li.id,$scope.li.fullname,$scope.li.ic_no,$scope.li.private_phone,$scope.li.office_phone,$scope.li.position,$scope.li.email,$scope.li.password ? I hope you can help me sir ..

          • Instead of doing console.error(error) do console.log(JSON.stringify(error)). Errors are objects and cannot be directly printed to your logs. You need to serialize them first.

            Once you do that, let me know the new error.

            Regards,

          • shahril

            ok … no error display at adb logcat ….

            V/sqlg ( 2333): prepare db 0x7fc45ddf0408 sql BEGIN

            V/sqlg ( 2333): sqlc_st_finish 0x7fc44c047148

            V/sqlg ( 2333): prepare db 0x7fc45ddf0408 sql INSERT INTO user_kdma (id,fullname,ic_no,private_phone,office_phone,position,email,password) VALUES (?,?,?,?,?,?,?,?)

            V/sqlg ( 2333): sqlc_st_finish 0x7fc44c047288

            D/SystemWebChromeClient( 2333): file:///android_asset/www/plugins/cordova-plugin-console/www/console-via-logger.js: Line 173 : [{“id”:”6″,”fullname”:”sadad”,”ic_no”:”12313″,”private_phone”:”2221″,”office_phone”:”4443″,”position”:”fff”,”email”:”[email protected]”,”password”:”12345″}]

            I/chromium( 2333): [INFO:CONSOLE(173)] “[{“id”:”6″,”fullname”:”sadad”,”ic_no”:”12313″,”private_phone”:”2221″,”office_phone”:”4443″,”position”:”fff”,”email”:”[email protected]”,”password”:”12345″}]”, source: file:///android_asset/www/plugins/cordova-plugin-console/www/console-via-logger.js (173)

            so how to parse JSON data to sqlite query ? because the data still not inserted into SQLite . I have no idea sir . 5 days thinks about this problem. haha

          • If you were getting [Object object] before, you must still be getting an error.

            [{“id”:”6″,”fullname”:”sadad”,”ic_no”:”12313″,”private_phone”:”2221″,”office_phone”:”4443″,”position”:”fff”,”email”:”af

            Is that what is in your error callback?

            For formatting JSON to SQL you’ll have to do that on your own. Several people have commented solutions to this on my other posts if you want to read the comments.

            Regards,

          • shahril

            Sir, my problem was solved … in controller.js I make my own code like this ..
            .success(function(data,status,headers,config){
            var user = data;

            /var dat=[{“id”:”6″,”fullname”:”sadad”,”ic_no”:”12313″,”private_phone”:”2221″,”office_phone”:”4443″,”position”:”fff”,”email”:”[email protected]”,”password”:”12345″}];
            for (i=0; i<dat.length; i++){
            var id = dat[i].id;
            var fullname = dat[i].fullname;
            var ic_no = dat[i].ic_no;
            var private_phone = dat[i].private_phone;
            var office_phone = dat[i].office_phone;
            var position =dat[i].position;
            var email = dat[i].email;
            var password = dat[i].password;
            }
            console.log(id,fullname,ic_no,private_phone);
            /
            //$scope.debtdata = angular.fromJson($scope.li);
            var query = “INSERT INTO user_kdma (id,fullname,ic_no,private_phone,office_phone,position,email,password) VALUES (?,?,?,?,?,?,?,?)”;
            $cordovaSQLite.execute(db, query, [id,fullname,ic_no,private_phone,office_phone,position,email,password]).then(function(res) {
            //$scope.sync.push({id: res.id,fullname: res.fullname,ic_no: res.ic_no,private_phone: res.private_phone,office_phone: res.office_phone,position: res.position,email: res.email,password: res.password});
            console.log(fullname);
            }, function (err) {
            console.error(err);
            });
            //$location.path(‘/app/browse’);
            })
            .error(function(data,status,headers,config){
            alert(‘error’);
            });

            and the data was succesfully insert into sqlite . I think maybe have another ways to make the data insert into sqlite apart of from the way I using. By the way, thanks in advance sir because take your time to help me and give some idea to solve this problem.

            Regards

          • shahril

            .success(function(data,status,headers,config){

          • shahril

            .controller(‘AppCtrl’, function($scope,$ionicPlatform,$location,$http,$ionicHistory, $ionicModal, $timeout,$cordovaSQLite) {

            $ionicHistory.nextViewOptions({

            });

            $ionicPlatform.ready(function(){

            });

  • Isabela Tonon

    I need your wallpaper photo!!!

    • You need to be a Pokemon master first 😉

      • Isabela Tonon

        Actually, I am! 😀 😀 😀

  • fabioi

    Hello Nic, I have a newbie question about HTTPs. I want to register a user from my Ionic app using HTTPS. I am new to security and don’t know exactly how to do it. I setup the Ionic proxy to point to my dev backend API
    eg:

    {
    “path”: “/api/v1”,
    “proxyUrl”: “https:///api/v1”
    },

    I installed a self signed SSL certificate on the dev backend.
    The problem is that I don’t’ know which steps I have to take to encrypt username and password when being posted. I was wandering if you could make a simple example / steps to achieve this . Thanks very much for your help and time! Fabio

    • I’m not sure why you need to create a proxy. Why not just communicate to the HTTPS URL directly? Communication should be encrypted by default when reaching a secure URL.

      Did I miss something?

      Regards,

      • fabioi

        Hi, thanks for your quick reply. Sorry the proxy is probably just a detail. I am using it in my development environment to avoid the CORS problems when I execute “ionic run -l”. The thing that is not clear to me is that when I post a user email and password to the backend they are not encrypted. I can read them in the content of the posted data. I am using https://ngrok.com/ to expose my vagrant VM to the internet and I am using their inspect tool that intercept all the requests, and as said I can read username and password content that is being posted to the VM. But I expect them to be encrypted if I am right).

        To post the data to the backend I use this AngularJS code:

        A “Register” resource

        .factory(‘Register’, function ($resource, ApiRegistrationEndpoint) {
        return $resource(‘http://192.168.0.4:8100/api/v1/authenticate/register’, {}, {

        That is translated with the proxy to the final url
        {
        “path”: “/api/v1/authenticate/register”,
        “proxyUrl”: “https:///api/v1/authenticate/register”

        },

        and then in the Controller here is how I post the data:
        Register.query(
        {
        name: $scope.auth.name,
        email: $scope.auth.email,
        password: $scope.auth.password,
        password_confirmation: $scope.auth.password_confirmation,

        …..

        But I think I am not doing it right since posted data is not encrypted. Any hint is very appreciated!

        • I’m not sure you can inspect requests like that. I believe by the time you receive and view the data it is already decrypted server side.

          What you probably want to do is install a software like Wireshark on your computer and inspect the traffic leaving your machine because that is where it matters. Client-side and server-side should be decrypted, while anything in between should be encrypted.

          I may be the wrong person to ask about sniffing data and making sure it is encrypted or not.

          Sorry,

          • fabioi

            Thanks anyway Nic! I ll give Wireshark a try.

          • Report back when you can. I’m curious to know what happens 🙂

  • Kartik

    Hello Nic, I have a .asmx webservice url in which there are many other operation like login. How do I add that to this url and will that work?

    • Login is a whole different topic, specially with a service like asmx or oauth. I’m done a plugin for oauth but I don’t know anything on asmx and can only assume it is as complicated as oauth.

      Sorry,

      • Kartik

        Absolutely fine. Asmx is an extension of a web service url generated when created a web service. I’m using that url in http get to get the credentials. I just want to know now how to change access control allow origin.

  • arun

    hello man, you video is so nic and also it help me. 🙂

    • Don’t test in a web browser. Build the app, whether it be an APK file or what Apple uses, and install it to your device or simulator. My guess is you’re trying to use ionic serve, ionic view, or ionic live-reload. All of which I recommend against.

      Web browsers are not a true experience.

      Regards,

      • arun

        Actually i done tis man thanks…..

  • arun

    Hi man,

    This is the logger for device

    Failed to load resource: net::ERR_CONNECTION_REFUSED http://localhost:8100/getVehicleLocations?userId=MSS

    No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin. console-via-logger.js:173

    No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin. console-via-logger.js:173

    No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.

    • I’ve responded to a few of your comments already and in all of them I told you to stop using the web browser. I see you are still using the web browser. I also see based on http://localhost:8100 that you are using ionic serve, ionic view, or ionic live-reload. I specifically said don’t use those.

      I can’t advise further until you take the advice I already gave you.

      Regards,

      • dcs3spp

        If you are running both server and emulator in you computer
        127.0.0.1:(port) will refer to the emulator itself and not to the
        server.The 10.0.2.2 is the solution to that problem.

        Hope this helps 🙂

  • Kartik

    Hi Nic, I am not able to pass variables as parameters during multiple parameter passing in my http request. However they’re working fine when the values are passed directly.

    • What kind of request? What do your logs say when it doesn’t work?

      • Kartik

        It just give an error. Not describing anything. It works if they’re directly passed on the url. But if i declare it as a variable is doesn’t take it.

        • You just said it gives you an error, yet you did not share it with me. I cannot help you further until I see your logs regardless on how descriptive they may be.

          Regards,

          • Kartik

            11-02 07:55:03.176: E/Web Console(3976): null at file:///android_asset/www/plugins/cordova-plugin-console/www/console-via-logger.js:173

          • That doesn’t help me. Please share your full logs.

  • Christian Ndoradoumngue

    Hello, Nic!
    Can you, please, take me through creating a Restful to allow my mobile app access MySQL?
    Thank you for your help

  • Rituraj

    Hey Nic,

    Its Rituraj again actually i am able to send HTTP get request on my server and also able to post something from my phone as well as my browser but the problem is that while sending request from my real device after sending few request say 5-10 it starts showing “your IP is blacklisted you will be redirected in 5 seconds” as error and when i left it and reopen my app it starts working again for 5-10 requests more since Nic i am planning to make it live very soon so can you tell me how to tackle this since when it will be live a lot of users will be sending a lot of requests so how to make it handle those requests without getting blacklisted .This is the site which also shows in error msg http://www.hostprotect.net/ and right now i am on a free server from http://www.hostinger.in/ .

    Thanks Nic

    • Sounds like you need to change some configurations on your server. Apache or Nginx (whatever you use) is probably configured to block requests when receiving many at once from the same IP.

      Regards,

  • nuruddin

    thank for this article , i have one question please ….
    if i wont to request to Api but response in zip /gzip file , how work with this case?? and thanks a lot 🙂

    • I have no idea what you’re asking. Want to try again?

  • Danilo Del Fio

    HI Nic. Thank you for your posts, but I have a question. Despite my co-workers have configured the server side of our application, I can’t call it with POST method, in fact, with GET method we have no troubles and also with browser call (and Postman) we don’t have any problems. The problems are ONLY with android device and POST request that return Forbidden response.
    Thanks

    • Have you checked your server side logs?

      • Danilo Del Fio

        Yep. My co-worker said me to use jsonp, but I think that it is better to modify server side cors policy, because Apache Tomcat seems not recognize “file//” origin like trusted one. What do you think about it?

        • Apache Cordova / Ionic apps do not suffer from CORS issues. This is only an issue when you test via a web browser or are serving the application via some kind of tool like Ionic Serve or Python.

          Can you confirm you are compiling the application and are installing it?

          Best,

          • Danilo Del Fio

            Yes. I can confirm it. The strange thing is that running the app on browser and on iOS emulator it works. I think that the server side part doesn’t recognize “file://” origin like trusted one and then it blocks the post calls. I don’t think that the solution is to use jsonp but to change server side configuration. Do you agree?
            Regards

          • Yes you should probably make some changes server side.

          • Danilo Del Fio

            Thank you so much Nic. You are the best!! 😀

  • Hello Nic ! I have learn a lot of things with you, but I have a last problem with my app before is release.

    I use HTTP Post for post to my Heroku Server. When I put variable direct in server like this (I use Postman) :

    // var user = “Mélanie”,

    // name = “Sortie au musée”,

    // tag = “servertest”;

    It’s work, but when I use (with click on ionic button) :

    var user = req.body.user,

    name = req.body.name,

    tag = req.body.tag;

    I have Internal error 500 …

    My controller :

    var SERVER_SIDE_URL = “https://myapp.herokuapp.com”;

    var pushUrl = SERVER_SIDE_URL + “/cancelpush”;

    $http.post(pushUrl, { params: { user: “Mélanie”, name: “Sortie à la salle”, tag: “servertest” } })

    .success(function(data) {

    console.log(“Success bro !” + data)

    }).error(function(data) {

    alert(“ERROR” + data);

    });

    My server :

    app.post(‘/cancelpush’, function(req, res) {

    var user = req.body.user,

    name = req.body.name,

    tag = req.body.tag;

    var sendNotification = function(data) {

    var headers = {

    “Content-Type”: “application/json”,

    “Authorization”: “Basic MyKey(Secret)”

    };

    var options = {

    host: “onesignal.com”,

    port: 443,

    path: “/api/v1/notifications”,

    method: “POST”,

    headers: headers

    };

    var https = require(‘https’);

    var req = https.request(options, function(res) {

    res.on(‘data’, function(data) {

    console.log(“Response:”);

    console.log(JSON.parse(data));

    });

    });

    req.on(‘error’, function(e) {

    console.log(“ERROR:”);

    console.log(e);

    });

    req.write(JSON.stringify(data));

    req.end();

    };

    var message = {

    app_id: “2549a5d6-75d0-4918-ba83-e4d3afd941d9”,

    contents: {“en”: user + ” not come ” + name + ” ! why … 😳”},

    tags: [{“key”: tag, “relation”: “=>”, “value”: tag}]

    };

    sendNotification(message);

    });

    Please help me (I can donate via Paypal if you do it ..) Thanks !

    • Can you share your application logs?

  • sufiyan khan

    hey Nic I am calling a rest api with post method the thing is when I call them they get loaded but it disturbs the rest of the code in android. Its working fine in ios and in web.Does ios and android treat the response diffrently??

    • Can you explain more on what you mean about it disturbing the Android code? Also what do your logs say?

      • sufiyan khan

        I am using chrome inspect for checking logs and I am running it on the device for testing.The log does not show anything.By disturbing I mean A div shows half and then it displays noting and the app stops working not crashes.I have attached the image the code in the red circle are two divs that I am calling or are being displayed when I click on them.When I click on them the get displayed but the div only shows in half and app stops working.I have attached the images. Please check if possible.

        Regards.

        • My guess is something has a bug in your toggleCategories() function. I know you say there are no logs, but can you please paste what ADB spits out at the time of the strangeness?

          Best,

          • sufiyan khan

            Hi Nic thanks for your response.I tried a lot but the error existed so I built the app from the scratch. My guess is that the problem was with css, now Its working fine.Thanks for your time.

          • Typing mistakes are the most unpleasant thing.

            I’m glad you got it working 🙂

  • McEileen

    Hi Nic,

    This tutorial is really helpful, thanks! Q: why do you put the http request in the controller? Why not put it in services? I’m asking because when I looked at the tabs template for an ionic app, they had an example factory in the services file, but said a call to return a JSON file could occur in services. I’m also used to thin controllers from working with MVC in Rails, which is obviously not AngularJS – still getting used to AngularJS. Thanks for your time!

    • You can put the request in a service. It is probably the better way to do things. I didn’t do that because services are over a lot of peoples head and out of the scope of what the tutorial is trying to prove. Trying to keep things as simple as possible 🙂

      Best,

  • Himanshu Rawat

    nice but it doesn’t work for me .

    when i get data another json file or server . nothing happens . please short out this problem

    • What do your logs say when you try to print out the retrieved data?

  • disqus_XB7wRzppMy

    Can you please post the code for the Web page (the code that sends the data to the App)? Is it PHP code? I can find the Ionic code lots of places, but the Web server side code is never shown. How can we learn/replicate this example if only half of the answer is shown? Thanks in advance.

    • This solution is not backend specific and out of the scope of the article.

      That said, I do provide the source code in my premium articles. It is one of the benefits to being a premium member.

      Best,

      • disqus_XB7wRzppMy

        Ugh okay. You know I purchased your basic Ionic class. I found it very educational, but I really really wish you would have created a second class that teaches how to “post” and “get” to/from a web server/database server using multiple examples (and explain the PHP coding, not just the Ionic code)

      • disqus_XB7wRzppMy

        done – where is this premium source code found?

  • disqus_XB7wRzppMy

    I copied this Ionic code exact, except I used different variable names. Here is the code:
    $scope.uploadItems = function() {
    console.log(“UploadItems START————-“);
    $http.get(“http://ecommerce.mywebsite.net/tsgnet”, { params: { “key1”: “value1”, “key2”: “value2” } })
    .success(function(data) {
    $scope.itemid = data.itemid;
    $scope.itemname = data.itemname;
    console.log(“ITEMID:” + data.itemid);

    Here is my error:
    ITEMID:undefined”, source: file//android_asset/www/js/controller.js (61)

    Does this “undefined” error mean there is something wrong with my Ionic code, or that when it did the “http.get”, my PHP posted undefined data? Please advise.

  • [email protected]

    Hi, thanks for ur tutorial this was really helpful.
    Q. i m using a ionic, angular build for the ios platform while sending a HTTPS PUT call it fails in the IOS (simulator,device). but when we run in the android device, web , emulator iT work fine. please help us out.
    Thanks for ur help

    • Without seeing any logs at all, my guess is that you’ve forgotten to include an ATS policy for iOS:

      https://www.thepolyglotdeveloper.com/2015/10/fix-ios-9-app-transport-security-issues-in-apache-cordova/

      • [email protected]

        Hi Nic, thanks for your reply.
        i watched your ATS video ,but on going through my solution about the key which u said in the video is already added. n i tried switching my metadata.

        even though not working
        i m able to call all the HTTP calls in IOS.
        but on calling HTTPS it returns 0 as status code

  • Ganesh Shetty

    how to post data to server