How to get back data from a Angularjs post request

Asked

Viewed 605 times

1

I have the following code:

$http.post('data.php').success(function(data) {
    return data;
}).error(function(data) {
    console.log(data);
}); 

How to handle data from this request?

I’m doing it this way:

var data = $scope.get_notas();

But when will I use the variable date she returns to me Undefined

  • Why don’t you just use the code on success? For example console.log(data) instead of return data;

1 answer

1


The problem is that the http call is asynchronous. One way to solve it would be to rewrite its function get_notas so that it performs a callback function:

$scope.get_notas = function(callback) {
    $http.post('data.php')
        .success(callback)
        .error(function(data) {
           console.log(data);
        }); 
}

And when calling it, pass the function that must be executed when completing the request:

$scope.get_notas(function(data) {
    console.log(data);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.