X
    Categories: AngularjsIonicPHP

Ionic angularjs php web api example

Ionic angularjs php web api example

Ionic angularjs php web api example, Ionic and angularjs is used to develop native or hybrid web applications. We need some server side scripting language to make some dynamic functionalities. Lets see how to write web api using php and how to access data by using api.

Ionic will act as a front end development tool, Php will act as server side language to make dynamic functionalities and angularjs will act as bridge between ionic and php.

How to write web api in php

Ionic with Routing basic example

In above examples you can find out how to write web api and how to make demo front end layout in ionic. Below we will see how to connect them both.

In this example we are going to insert users and list users by using web service.

Here you can see the basic layout of demo app and here we are continuing with one extra nav called Users

Step 1 : Create Nav for Users tab

tabs.html

<ion-tab title="Users" icon="ion-person-stalker" ui-sref="tabs.users">
            <ion-nav-view name="users-tab"></ion-nav-view>
        </ion-tab>

Step 2 : Create Route

app.js

.state('tabs.users', {
        url : '/users',
        views : {
          'users-tab' : {
            templateUrl : 'templates/users.html',
            controller: 'UsersController'
          }
        }
      })

Step 3 : Create Template

<ion-view view-title="Users">
	<ion-nav-bar class="bar-positive nav-title-slide-ios7" align-title="center">
	        <ion-nav-buttons side="right">
	          <div class="buttons">
		        <button class="button button-icon ion-compose" ng-click="openModal()">
		        </button>
		</div>
	        </ion-nav-buttons>

      	</ion-nav-bar>
	<ion-content>
		<ion-list>
			<ion-item ng-repeat = " user in users" >{{  user.name }} ~ {{ user.email  }} </ion-item>
		</ion-list>
	</ion-content>
</ion-view>

On the load we will get all listed users and will display in ng-repeat loop. [getAllUsers()]

In my example I am going to show modal pop for user insertion form. So I will append the modal template on the time of page load by using $ionicModal injection. You can see how to do that below.

Step 4 : Write UsersController as per the requirement

.controller('UsersController', function ($scope, $http, $ionicModal) {
    var users = [];

    $scope.getAllUsers = function() {
        $http({
          method: 'GET',
          headers: {
              "Content-Type": "application/json",
              "Accept" : "application/json"
          },
          url: 'http://****************/api/users/list'
        }).then(function successCallback(response) {
              $scope.users =  angular.fromJson(response).data; 
          }, function errorCallback(response) {
          });
    };

    $scope.getAllUsers();

    $ionicModal.fromTemplateUrl('templates/user-create-modal.html', {
        scope: $scope,
        animation: 'slide-in-up'
      }).then(function(modal) {
        $scope.modal = modal;
      });
    $scope.openModal = function() {
      $scope.modal.show();
    };
    $scope.hide = function() {
      $scope.modal.hide();
    };
   
})

Step 5 : Create user-create-modal template

<ion-modal-view>
    <ion-header-bar class="bar-positive">
      <h1 class="title">Create User</h1>
      <button class="button button-clear button-primary" ng-click="modal.hide()">Cancel</button>
    </ion-header-bar>
    <ion-content>
    	<form name="userCreate" ng-submit="createContact(newUser)"  enctype="multipart/form-data" >
	      <div class="list">
	            <label class="item item-input">
	              <span class="input-label">Full Name</span>
	              <input ng-model="newUser.name" type="text" placeholder="Enter Full Name" >
	            </label>
	            <label class="item item-input">
	              <span class="input-label">Username</span>
	              <input ng-model="newUser.username" type="text" placeholder="Enter Username" >
	            </label>
	            <label class="item item-input">
	              <span class="input-label">Email</span>
	              <input ng-model="newUser.email" type="text" placeholder="Enter Email" >
	            </label>
	            <label class="item item-input">
	              <span class="input-label">Password</span>
	              <input ng-model="newUser.password" type="password" placeholder="Enter Password" >
	            </label>
	            <label class="item item-input">
	              <span class="input-label">Avatar</span>
	              <input ng-model="newUser.avatar" type="file" placeholder="Enter Message" >
	            </label>
	            <button class="button button-full button-positive">Create</button>
	       </div>
	</form>
    </ion-content>
  </ion-modal-view>

Step 6 : Write createContact() function inside UsersController

$scope.createContact = function(u) {      
           //console.log(JSON.stringify(u));
            $http.post(
                'http://****************/api/users/create',
                JSON.stringify(u),
                {
                    headers: {
                       "Content-Type": "application/json",
                    }
                }
            ).success(function (data) {
              console.log(data);
              $scope.users.push( angular.fromJson(data) )
            });
      //$scope.users.push({ name: u.name, email : u.email, message : u.message });
          $scope.modal.hide();
          angular.copy({}, u);
    };

You can see how to write web api in php @http://www.17educations.com/php/php-restful-web-services/

Additional Information :

Note * This is how am receiving and inserting data from api. You can modify it as per your logic

How to get posted data in php api 

$json = file_get_contents('php://input');
$userData = json_decode($json, TRUE);

How bind param dynamically in php pdo

$bind = ':'.implode(',:', array_keys($userData));
$sql = "INSERT INTO users_api(". implode(',', array_keys($userData)) .") VALUES (".$bind.")";                            
$stmt = $this->conn->prepare($sql);
foreach($userData as $Name => &$Value){
            $stmt->bindParam(':'.$Name, $Value, $this->getParam($Value));
        }                                    
$stmt->execute(); 

public function getParam($value) {
	if(is_int($value))        { $param = PDO::PARAM_INT; }
           elseif(is_bool($value))   { $param = PDO::PARAM_BOOL; }
           elseif(is_null($value))   { $param = PDO::PARAM_NULL; }
           elseif(is_string($value)) { $param = PDO::PARAM_STR; }
           else { $param = FALSE;}
           return $param;
}

Some times you will face below issue in console at ajax call ( GET , POST )

XMLHttpRequest cannot load http://*********/api/users/list. No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Origin ‘http://localhost:8100’ is therefore not allowed access.

To fix this

Add below lines in your index.php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

Ionic angularjs php :  Output

Result of ionic angularjs php example in PostMan :

 

Hope it will help someone.

 

Marimuthu: