1

i'm using angularJS and SLIM PHP restful server, the PHP service is working and actually i have already used $http.get() with no problems in this application ... But now a strange thing is happening, i created a new function in the same way that the others, and it get .success(function(data)) with no problems, i actually can console.log(data) and it shows the right results, but when .success() finish and return, i recieve a undefined result. ps: there is no error in browser console.

    var markerOptions = [];
    loadMarkers();
    console.log(markerOptions);

    function loadMarkers() {
    $http.get('http://localhost/rest/getMarkers').success(function(response){
            console.log(response);
            markerOptions = response;
    });
}
  • Console.log() inside success() return the right data
  • Console.log() after loadMarkers() return undefined
Felipe
  • 213
  • 1
  • 2
  • 12
  • 3
    Since `$http.get` is asynchronous, its results are not available immediately where your synchronous code picks up. This is why your `console.log` is empty outside of `success`. – Marc Kline May 09 '14 at 23:35
  • See: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Marc Kline May 09 '14 at 23:37
  • 3
    BTW, this is a very common painpoint that is well-worth the headache of wrapping your head around once and for all. – Marc Kline May 09 '14 at 23:46
  • humm, i get it, thank you very much Marc. I'm trying to realise a solution for this in angular now.. but you show me the path, ty again. – Felipe May 09 '14 at 23:54
  • 1
    The top answer in the article above is great as a primer, and then you can read the [documentation on `$q`](https://docs.angularjs.org/api/ng/service/$q) in Angular for more food for thought. – Marc Kline May 09 '14 at 23:57

1 Answers1

4

@MarcKline's comments are correct. Anyways, following what I think you're trying to achive by this piece of code of yours, you can assign the returned data from the ajax response to a scope variable (assuming you're using $scope), e.g $scope.markerOptions = response. You can declare markOptions as a scope variable by var $scope.markOptions = [] (...and, of course, log it by console.log($scope.markOptions) accordingly). Also, define $scope.loadMarkers = function() {...} and call it by $scope.loadMarkers()

The scope will be updated as soon as the client-side gets its ajax response. Hope it helps your current needs in addition to a better understanding of javasciprt's async approach that some of its principles were explained to you by the comments.

Kludge
  • 2,653
  • 4
  • 20
  • 42
  • I try it, and doesn't work, i try use .then() too ... but still not working :( – Felipe May 10 '14 at 00:33
  • 2
    define loadMarkers as a scope function by $scope.loadMarkers = function() {...} and call it by `$scope.loadMarkers()` – Kludge May 10 '14 at 00:36