0

I have this jQuery function:

var searchResultsCounter = 0;
function searchPerson(filterText){
    //code
    $.ajax({
        type: "GET",
        dataType:"json",
        url: "res/main.php",
        data: { command : "loadPeople",
                filter: filterText },
        success: function( people ){
            for(var i = 0; i< people.length; i++){
                //code  
            }   
            searchResultsCounter = people.length;
            console.log(searchResultsCounter);  
        }
    }); 
console.log(searchResultsCounter);
return searchResultsCounter;
}

In the first console log, my searchResultsCoutner has a good value, at the second log, it becomes 0. Why is this happening?

Victor
  • 13,914
  • 19
  • 78
  • 147
  • Second one as in after the Ajax function? You know it is asynchronous right? So the last console.log in your code could be triggered before the one in your Ajax function. – putvande Jul 27 '13 at 12:00
  • Duplicate: http://stackoverflow.com/questions/9791734/javascript-variable-scope-inside-ajax-function – krillgar Jul 27 '13 at 12:02
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – A. Wolff Jul 27 '13 at 12:03

2 Answers2

5

The ajax request is executed asynchronously, so the success callback function which tries to alter the variable will be executed later.

Your function simply returns 0. You have to rewrite your code that it works an asynchronous way. One way would be to pass a callback function to searchPerson as a parameter.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
1

Return from searchPerson() function the promise interface ($.ajax) and use returned result once deferred is resolved:

function searchPerson(filterText) {
    //code
    return $.ajax({
        type: "GET",
        dataType: "json",
        url: "res/main.php",
        data: {
            command: "loadPeople",
            filter: filterText
        }
    });
}

$.when(searchPerson(filterText)).done(function (data) { 
    /*SUCCESS*/
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155