Allenph
Allenph

Reputation: 2015

Problems with a simple Angular JS $http object response?

I've done quite a lot of posting with Angular, however I've never received a response and I'm having trouble with it.

PHP

<?php
    return "testing";
?>

I'm actually unsure whether I should use return or echo here. I've tried both. And the Angular documentation doesn't provide much insight into the server side scripts.

This is in my Controller:

this.acquireImages = function() {
        $http.get("resources/php/gallery.php").success(function(response){
            this.returnData = response.data;
        });
    };
    this.acquireImages();

I've defined returnData before just to make sure it wasn't something simple like not displaying the correct variable, etc.

I've seen the documentation here and I'm following as well as I can, but I can't seem to get this simple example to work.

Upvotes: 1

Views: 99

Answers (2)

Paul Boutes
Paul Boutes

Reputation: 3305

On the PHP side, you have to echo and not return the data.

If you use the return statement, you will return some data at the server level.

So you need to write your data.

PHP

<?php 

    echo 'hello world !';


 ?>

In the success callback, the response is our raw data.

But, you should wrap your api call into a service, then you will get :

Controller

(function(){

    function Controller(Service){


        //Our callback
        function print(data){
            console.log(data);
        }

        //Call service with our callback
        Service.get(print);

    }

    angular
    .module('app')
    .controller('Ctrl', Controller);

})();

Service

(function(){

    function service($http){

        this.get = function(callback){
            $http.get('server.php').success(function(data){
                callback(data);
            });
        }

    }

    angular
        .module('app')
        .service('Service', service);

})();

Upvotes: 2

kubut
kubut

Reputation: 315

Inside $http.get function this mean something else than outside. You should do something like that:

var that = this;
$http.get("resources/php/gallery.php").success(function(response){
    that.returnData = response.data;
});

Also in PHP you should do echo 'something', becouse in Angular you get the same content as your browser when you visit this URL

Upvotes: 1

Related Questions