Unable to post form data to PHP API in ionic

2019-09-09 06:13发布

问题:

// 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() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})
.controller('AppCtrl', function($scope, $http) {
    $scope.data = {};
 
    $scope.submit = function(){
        var link = 'api_url';
 
        $http.post(link, angular.toJson({key: $scope.data.key,mac_address : $scope.data.mac_address})).then(function (res){
            $scope.response = res.data;
        });
    };
});
<!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 rel="manifest" href="manifest.json">

    <!-- un-comment this code to enable service worker
    <script>
      if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('service-worker.js')
          .then(() => console.log('service worker installed'))
          .catch(err => console.log('Error', err));
      }
    </script>-->

    <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>
	<html>
 <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="key" placeholder="enter username" ng-model="data.key">
                    </label>
   <label class="item item-input item-stacked-label">
                        <span class="input-label">Username</span>
                        <input type="text" name="mac_address" placeholder="enter username" ng-model="data.mac_address">
                    </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>

I used Json.stringfy , angulartojson etc but nothing works . I am trying to run this Api on localhost and all access controls headers are given in the api. Api accepts two parameters(post method) save it to database and return json data with two keys. API is unable get those two parameters

回答1:

To make a post you must have the following structure:

.controller('AppCtrl', function($scope, $http) {

    $scope.submit = function(){
        var link = 'api_url';
        var data = {key: $scope.data.key, mac_address : $scope.data.mac_address};
        $http.post(method : 'POST', url : link, data : JSON.stringify(data), dataType : 'json', contentType: 'application/json')).then(function (res){
            $scope.response = res.data;
        });
    };
 });


回答2:

Thanks for the answer. Actually the problem was i am not setting the header variables in php api properly. I solved it using below code.

    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day