0

Having some trouble understanding how to mix AngularJS and PHP. I am initially just trying to have an AngularJS factory make a call to a PHP file (which grabs a query), then push it back to my AngularJS factory where a Controller can use the data.

Here is what I have so far, and this gives me "undefined" when I try to console.log the result.

Factory

app.factory("PlantServiceLIVE", function($http) {
  var mData = {};
  $http.get('pages/getplants.php').success(function(data) {
    mData.data = data;
  });
  return mData;
});

Controller

app.controller('TestController', function($scope, $http, PlantServiceLIVE) {
  $scope.Plants = PlantServiceLIVE.mData;
  console.log(JSON.parse($scope.Plants));
});

PHP (just verified that the below works tooo)

$sql = "SELECT * FROM PlantTable";
$result = $conn->query($sql);
echo json_encode($result);

Not sure what exactly I am doing wrong, first time doing this.

The only developer console errors I get are SyntaxError: Unexpected token u, which from what I read just means the data is undefined.

2 Answers 2

1

The problem is not about angular but more about how Ajax requests work.

AJAX requests work asynchronously, which means that the response is not immediately available. What you need to do is to prepare your code to be notify when the response is ready. In vanilla javascript, you'd use callback to get notified, angular uses promises

To get it work you need to change your code a little. Factory

app.factory("PlantServiceLIVE", function($http) {
  var mData = {
    gettingPlants: function(){
      return $http.get('pages/getplants.php')
    }
  };

  return mData;
});

Controller

app.controller('TestController', function($scope, $http, PlantServiceLIVE) {
  PlantServiceLIVE.gettingPlants.then(function(response){
    console.log(JSON.parse(response.data));
  });

});
Sign up to request clarification or add additional context in comments.

6 Comments

Hmmm, interesting! I am still getting undefined for the console.log however :/ Does my PHP return look okay?
There was a typo PlantServiceLIVE.gettingPlan -> PlantServiceLIVE.gettingPlans. I'm not a PHP guy. It would be misleading for me to say something about it. If you're using chrome/firefox, I would recommend checking out what you getting from your server.
Yup, I caught the typo before running it. And when I do the echo I am getting data back. If it stays as is, then it returns some null things, but when I actually push the result into a php array, then print it, I get all the information. (I also tried encoding the array back though too)
I think the response is not properly formatted as json. That's where the syntax error comes from
Could you please provide your server response? then takes two functions as parameters. success and failure callbacks. Add the second function to find out whether the request is failing.
|
1

I think the main problem is you're not actually calling $http.get(), you're just defining it. Also, you should read more about async calls in Angular (they're a real pain, but they get pretty cool after you get a grasp of them).

This got me started: http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/ (just make sure you stay away from their official documentation; it's a real mess that's either overcomplicated or over-simplified).

Anyways, for your problem:

Try this in your factory:

app.factory("PlantServiceLIVE", function($http) {
  var mData = {
        get_data : function(){
            return $http.get('pages/getplants.php').success(function(data) {
                     return mData.data = data;
                   });
        }
      };

  return mData;
});

Then get the data (after you've received it) in your controller, like this:

app.controller('TestController', function($scope, $http, PlantServiceLIVE) {
  $scope.click_me = function(){
    var wait = PlantServiceLIVE.mData();
    wait.then(function(data){
      console.log(data); //you should have your data here.
      $scope.Plants = data;
    });
  }
});

Then make it touchable with

<button ng-click="click_me()">Gimme plants</button>

3 Comments

Just gave this a shot and it still returns undefined for console.log. :( Does my PHP return look okay?
I am also actually getting the following: undefined is not a function, most likely in reference to the button. But when I put an alert within the click_me, I get that alert message, so I know that it is hitting the function just fine from the button.
i forgot a "}" in the code above. Could you post the exact message you're getting in the console? (expanded and all). Also, post the entire code you're trying to get to work. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.