Victor
Victor

Reputation: 14573

Variable becomes undefined during my function

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?

Upvotes: 0

Views: 993

Answers (2)

A. Wolff
A. Wolff

Reputation: 74420

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*/
});

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96258

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.

Upvotes: 5

Related Questions