0

After I struggling with some errors, later I've succeeded create PHP connector with my live hosting mysql, but unfortunately my AngularJS failed to connect. I create php with json format called json.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("domain","user","pass","db_name");
$result = $conn->query("SELECT UID, Name, City, Country FROM records");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"UID":"'  . $rs["UID"] . '",';
$outp .= '{"Name":"'  . $rs["Name"] . '",';
 $outp .= '"City":"'   . $rs["City"]        . '",';
$outp .= '"Country":"'. $rs["Country"]     . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>

my controller

var testAppApp = angular.module('testAppApp', []);
testAppApp.controller('SimpleController', function ($scope, $http) {
        $http.get('json.php')
        .then(function(takeprocess) {
            $scope.customers = takeprocess.data.records;
        });
});

My index.html

<html ng-app="testAppApp">
<head>
..................
..................
</head>
<div ng-controller="SimpleController">
Search <input type="text" ng-model="filter.name" />
<ul>
<li ng-repeat="cust in customers | filter:filter.name">{{cust.UID}} -   
{{cust.Name}} - {{cust.City}} - {{cust.Country}}</li>
</ul>
</div>

<script src="bower_components/angular/angular.js"></script>
<script src="scripts/controllers/SimpleController.js"></script>
</body>
</html>

Actually, when I run json.php in MAMP (for testing) using Apache Server the data show like below

{"records":[{"UID":"1",{"Name":"Konohamaru","City":"Leaf Village","Country":"Konoha District"},{"UID":"2", {"Name":"Gaara","City":"Sand Village","Country":"Sand Desert Union"}]} 

This mean, I have no issue with live hosting sql server, authentication, or any. This is works well. But strangely enough when I access the php file directly with "localhost:9000/json.php" the code can't show anything, instead the browser downloading my script.

NOTE : My console not show error(s) notification too, but still when I run "Grunt Server" and take the process to open localhost:9000 my App didn't show any dummy data from my live host DB. But when I testing with data.json, for the purpose if my code actually works, voila the good thing happen, my data showing. I still confuse, where I was wrong in this process, please help. Thanks in advance

1 Answers1

0

Okay, I made it self finally. First, I don't know it proxy issue or what. But since I know grunt can't execute PHP file (before modified), later I search where the wrong my project.

First, I've indicated Grunt Server can't execute PHP, so I must modify gruntfile.js based on this article "Use PHP with your Yeoman dev server" but honestly, there is no softly step by step how and where you can put your code. In shortcut, here I put my code in Gruntfile.js (near top)

// Generated on 2017-03-13 using generator-angular 0.16.0
'use strict';
var lrSnippet = require('grunt-contrib-       
livereload/lib/utils').livereloadSnippet;
var gateway = require('gateway');
var mountFolder = function (connect, dir) {
return connect.static(require('path').resolve(dir));
}; 

And here....

 livereload: {
    options: {
      open: true,
      middleware: function (connect) {
        return [
          lrSnippet,
          gateway(__dirname + '/app', {
          '.php': 'php-cgi'}),
          mountFolder(connect, '.tmp'),
          mountFolder(connect, 'app'),
          connect.static('.tmp'),
          connect().use(
            '/bower_components',
            connect.static('./bower_components')
          ),
          connect().use(
            '/app/styles',
            connect.static('./app/styles')
          ),
          connect.static(appConfig.app)
        ];
      }
    }
  },

In specific section, I add below return [ .....

lrSnippet,
          gateway(__dirname + '/app', {
          '.php': 'php-cgi'}),
          mountFolder(connect, '.tmp'),
          mountFolder(connect, 'app'),

After that, I edit my json.php like below

<?php
//open connection to mysql db
$connection = mysqli_connect("hosting","username","pass","db_name") or die("Error " . mysqli_error($connection));

//fetch table rows from mysql db
$sql = "select * from records";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
    $emparray[] = $row;
}

header('Content-Type: application/json');
echo json_encode($emparray);

//write to json file
//$fp = fopen('data.json', 'w');
//fwrite($fp, json_encode($emparray));
//fclose($fp);

//close the db connection
mysqli_close($connection);
?>

And edit my controller little bit

var testAppApp = angular.module('testAppApp', []);
testAppApp.controller('SimpleController', function ($scope, $http) {
        $http.get('json.php')
        .then(function(takeprocess) {
            $scope.customers = takeprocess.data;
        });
});

Later, I start "Grunt Build" and try "Grunt Server". My App show in localhost:9000 but still blank, but when I change my Wifi. My App works like charm, I can connecting my Live hosting MySQL with my local Grunt.

But, it seems I have complicated thing, My Grunt not supporting to read PHP before, and I suspect my network not stable or have proxy issue, I don't know. But when I try again, clean my project with default setting (without gateway setting in Gruntfile.js). My app have error(s) again.

I hope this help to everyone who have same experience with me.

NOTE : There are several dependencies you must done, Install gateway in your project not global

npm install gateway

If you notice here...

var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;

variable LrSnippet need dependencies grunt-contrib-
livereload, just do

npm install grunt-contrib-livereload

sudo if needed