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
5
  • 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. Commented May 9, 2014 at 23:35
  • See: stackoverflow.com/questions/14220321/… Commented May 9, 2014 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. Commented May 9, 2014 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. Commented May 9, 2014 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 in Angular for more food for thought. Commented May 9, 2014 at 23:57

1 Answer 1

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.

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

2 Comments

I try it, and doesn't work, i try use .then() too ... but still not working :(
define loadMarkers as a scope function by $scope.loadMarkers = function() {...} and call it by $scope.loadMarkers()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.