0

I know this might be considered as duplicate, but I could not find a solution for my function below:

    function countNoFilters(keyword){

    keyword = typeof keyword !== 'undefined' ? keyword : "keyword="+$("#keyword-hidden").val();

    var getResults = $.ajax({
        type:"GET",
        url:"",
        data:keyword

    });

    getResults.done(function(data){
        var results = $(data).find(".class").length;
        return results;
    });
} 

How can I get my function 'countNoFilters("keyword")' to return the return from the .done function inside ? It would be nice if someone could write a working example for my specific function.

Sander
  • 95
  • 2
  • 6
  • 1
    You **can not** return the result of an asynchronous function, that's why this is a 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), that question shows you how it should be done, not to do it the way you want, as that's impossible, the only option would be to make it synchronous, and that's not really a viable option. – adeneo Dec 26 '14 at 00:01
  • thank you @adeneo for the great topic link.... I will restructure my code – Sander Dec 26 '14 at 00:05

2 Answers2

-1

I'm not sure if this is what you want, but you could use a function variable and inside the done function you just set the gresult variable which will be returned at the end of the countNoFilters function:

function countNoFilters(keyword){

    var gresult;

    keyword = typeof keyword !== 'undefined' ? keyword : "keyword="+$("#keyword-hidden").val();

    var getResults = $.ajax({
        type:"GET",
            url:"",
            data:keyword

        });

    getResults.done(function(data){
            var results = $(data).find(".class").length;
            gresult = results;
        });

    return gresult;
} 
Andrew V
  • 522
  • 10
  • 24
  • **gresult** is undefined when calling the function countNoFilters(); has something todo with te .done scope... – Sander Dec 25 '14 at 23:56
-1

You need to set the async:false. Please run the following function:

function countNoFilters(keyword){

    var gresult;

    keyword = typeof keyword !== 'undefined' ? keyword : "keyword="+$("#keyword-hidden").val();

    var getResults = $.ajax({
        type:"GET",
            url:"",
            data:keyword,
            async:false
        });

    getResults.done(function(data){
            var results = $(data).find(".class").length;
            gresult = results;
        });

    return gresult;
}