Labels

Learn the powerful enterprise adaptable database:

Getting Started With ADABAS & Natural

Tuesday, January 10, 2017

111 Ionic with Google Form and Google Sheet


.
111 Ionic with Google Form and Google Sheet

This tutorial demonstrates how to post responses to Google Form and view them back via Google Sheet API.

1) Start with startup codes.

Rename as 111 Ionic with Google Form and Google Sheet 1

1) Create Google Form

Assume that we are collecting Name, Email and Message.
Browse http://drive.google.com and create a new Google Form.
Use Web Browser Developer Console to get the field ids
Name = entry.1596847310
Email = entry.1635092957
Message = entry.1714158145

2) Create New Google Sheet to store responses.

URL:

3) Test the Google Form URL and field id using Chrome Postman Extension.

Postman should received a positive response.
Google Sheet should display the submitted response.

4) Add Codes To Post Data

HTML
<html>
<head>
    <meta charset="utf-8">
    <title>Diary</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <!-- Internal Library
    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <script src="lib/ionic/js/ionic.bundle.js"></script>
    -->
    <!-- Cloud Library -->
    <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
    <script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
    <!-- Needed for Cordova/PhoneGap (will be a 404 during development) -->
    <script src="cordova.js"></script>
</head>
<body ng-app="app">
    <div>
        <div>
            <ion-nav-bar class="bar-stable">
                <ion-nav-back-button></ion-nav-back-button>
            </ion-nav-bar>
            <ion-nav-view></ion-nav-view>
        </div>
    </div>
    <script id="home.html" type="text/ng-template">
        <ion-view title="Home" id="page1">
            <ion-content padding="false" scroll="false" class="has-header">
                <ion-scroll class="top-container" delegate-handle="messagelist">
                    <ion-list>
                        <ion-item ng-repeat="entry in entries">
                            <h2>{{entry.name}}</h2>
                            <p>{{entry.email}}</p>
                        </ion-item>
                    </ion-list>
                </ion-scroll>
                <form class="bottom-form" ng-submit="postMessage()">
                    <br/>
                    <label class="item item-input">
        <span class="input-label">Name</span>
        <input type="text" placeholder=""
        ng-model="data.name">
      </label>
                    <label class="item item-input">
        <span class="input-label">Email</span>
        <input type="text" placeholder=""
        ng-model="data.email">
      </label>
                    <label class="item item-input">
        <span class="input-label">Message</span>
        <input type="text" placeholder=""
        ng-model="data.message">
      </label>
                    <button class="button button-positive  button-full">Submit</button>
                </form>
            </ion-content>
        </ion-view>
    </script>
</body>
</html>
CSS (no changes)
.top-container{
    height: calc(100% - 220px);
   overflow:scroll;
}
.bottom-form{
    position:absolute;
    bottom:0px;
    display:block;
    width:100%;
    background-color:lightgrey;
    button{
        margin:0px !important;
    }
}
/*
the following css codes overcome
the double scroll bar issues
*/
::-webkit-scrollbar,
*::-webkit-scrollbar {
    display: none;
}
JS
angular.module('app', ['ionic'])
.controller('homeCtrl', ['$scope', '$ionicScrollDelegate','$http',
function ($scope,$ionicScrollDelegate,$http) {
  $scope.entries=[];
  $scope.data={};
  $scope.addMessage=function(){
    $scope.entries.push($scope.data);
    $scope.data={};
    $ionicScrollDelegate.$getByHandle('messagelist').scrollBottom();
    console.log($scope.entries);
  }
  $scope.postMessage = function (){    
    var jsonData={
      "entry.1596847310":$scope.data.name,
      "entry.1635092957":$scope.data.email,
      "entry.1714158145":$scope.data.message
    };
    console.log(jsonData);
  var strData = Object.keys(jsonData).map(function(key){
  return encodeURIComponent(key) + '=' + encodeURIComponent(jsonData[key]);
}).join('&');


   $http({
      method: 'POST',
      url: 'https://docs.google.com/forms/d/e/1FAIpQLSdneWWfhgPch7eOuFKRgk7YFz-GpD2eOiamJfe7_EY-6hmfvg/formResponse',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
      data:strData
   })
   .then(function mySucces(response) {
        console.log("success:" + response);
    }, function myError(response) {
        console.log("error:" + response);
    });
}  
}])
   
.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
      .state('home', {
    url: '/page1',
    templateUrl: 'home.html',
    controller: 'homeCtrl'
  })
$urlRouterProvider.otherwise('/page1')
});

5) Add codes to get response data

FORK: http://codepen.io/notarazi/pen/zNVbZy  and rename as 111 Ionic with Google Form and Google Sheet 2
Publish your Google Sheet.
Find your feed link from the following URL.
Look for the link containing the string feeds/list.
E.g:
Change basic to values.
Append ?alt=json to the end of the URL String so that you get JSON format.
HTML
<html>
<head>
    <meta charset="utf-8">
    <title>Diary</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <!-- Internal Library
    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <script src="lib/ionic/js/ionic.bundle.js"></script>
    -->
    <!-- Cloud Library -->
    <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
    <script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
    <!-- Needed for Cordova/PhoneGap (will be a 404 during development) -->
    <script src="cordova.js"></script>
</head>
<body ng-app="app">
    <div>
        <div>
            <ion-nav-bar class="bar-stable">
                <ion-nav-back-button></ion-nav-back-button>
            </ion-nav-bar>
            <ion-nav-view></ion-nav-view>
        </div>
    </div>
    <script id="home.html" type="text/ng-template">
        <ion-view title="Home" id="page1">
            <ion-content padding="false" scroll="false" class="has-header">
                <ion-scroll class="top-container" delegate-handle="messagelist">
                  <ion-refresher
    pulling-text="Pull to refresh..."
    on-refresh="doRefresh()">
  </ion-refresher>
                    <ion-list>
                        <ion-item ng-repeat="entry in entries">
                            <h2>{{entry.gsx$yourname.$t}}</h2>
                            <p>{{entry.gsx$youremail.$t}}</p>
                            <p>{{entry.gsx$yourmessage.$t}}</p>
                        </ion-item>
                    </ion-list>
                </ion-scroll>
                <form class="bottom-form" ng-submit="postMessage()">
                    <br/>
                    <label class="item item-input">
        <span class="input-label">Name</span>
        <input type="text" placeholder=""
        ng-model="data.name">
      </label>
                    <label class="item item-input">
        <span class="input-label">Email</span>
        <input type="text" placeholder=""
        ng-model="data.email">
      </label>
                    <label class="item item-input">
        <span class="input-label">Message</span>
        <input type="text" placeholder=""
        ng-model="data.message">
      </label>
                    <button class="button button-positive  button-full">Submit</button>
                </form>
            </ion-content>
        </ion-view>
    </script>
</body>
</html>
JS
angular.module('app', ['ionic'])
.controller('homeCtrl', ['$scope', '$ionicScrollDelegate','$http',
function ($scope,$ionicScrollDelegate,$http) {
  $scope.entries=[];
  $scope.data={};
  $scope.addMessage=function(){
    $scope.entries.push($scope.data);
    $scope.data={};
    $ionicScrollDelegate.$getByHandle('messagelist').scrollBottom();
    console.log($scope.entries);
  }
  $scope.postMessage = function (){    
    var jsonData={
      "entry.1596847310":$scope.data.name,
      "entry.1635092957":$scope.data.email,
      "entry.1714158145":$scope.data.message
    };
    console.log(jsonData);
  var strData = Object.keys(jsonData).map(function(key){
  return encodeURIComponent(key) + '=' + encodeURIComponent(jsonData[key]);
}).join('&');
   $http({
      method: 'POST',
      url: 'https://docs.google.com/forms/d/e/1FAIpQLSdneWWfhgPch7eOuFKRgk7YFz-GpD2eOiamJfe7_EY-6hmfvg/formResponse',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
      data:strData
   })
   .then(function mySucces(response) {
        console.log("success:" + response);
        $scope.doRefresh();    
    }, function myError(response) {
        console.log("error:" + response);
        $scope.doRefresh();  
    });
    $scope.data={};
}  
   
$scope.$on('$ionicView.enter', function(){
    $scope.doRefresh();
});    
    $scope.doRefresh = function() {
    var url='https://spreadsheets.google.com/feeds/list/1uk5u_6QijDN095NELFGkMe6NIdKJFWh_1wqStS9J668/our66d4/public/values?alt=json';
    $http.get(url)
      .then(function(resp) {
        console.log('Success', resp);    
        $scope.entries = resp.data.feed.entry;
        $ionicScrollDelegate.$getByHandle('messagelist')
         .scrollBottom();    
        console.log($scope.entries);
        }, function(err) {
        // err.status will contain the status code
        console.error('ERROR', err);
      })
     .finally(function() {
       // Stop the ion-refresher from spinning
       $scope.$broadcast('scroll.refreshComplete');
     });
  };
}])
   
.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
      .state('home', {
    url: '/page1',
    templateUrl: 'home.html',
    controller: 'homeCtrl'
  })
$urlRouterProvider.otherwise('/page1')
});
CODEPEN:

DEMO:
.

1 comment:

  1. Thank you very much Razi! Your post was really helpful!

    ReplyDelete