user714852
user714852

Reputation: 2154

Returning result from jquery ajax request to a variable rather than firing a function

I'm experimenting with MCV using jquery. I'm making a call to an api, which returns data - what I want to do is return the data to a variable rather than call an additioanl function within my model. The following code doesn't do what I wish though (the_data = result). Any ideas how I can achieve this?

function lookForSomething()
{
    var the_data = $.ajax({ type: "GET", 
                            url: TheUrl, 
                            dataType: "jsonp", 
                            success: function(result) { return result; } 
                            });
    return the_data;
}

Many thanks, J

Upvotes: 0

Views: 208

Answers (2)

rkw
rkw

Reputation: 7297

You are probably looking for deferred objects:

function lookForSomething()
{
    var the_data;
    $.when(
        $.ajax({ type: "GET", 
                            url: TheUrl, 
                            dataType: "jsonp", 
                            success: function(result) { the_data=result; } 
                            });
    ).done(function() {
        return the_data;
    }).fail(function() {
        return '';
    });
}

Keep in mind that this is still asynchronous, so when you make a call for var ddd = lookForSomething();, ddd will not have the value you expect since the call may still be running. The only reason I brought up $.when() is because it seems like you require a lot of dependencies. $.when() allows you to wait for multiple ajax commands.

Upvotes: 0

Michael Lorton
Michael Lorton

Reputation: 44376

If understand you correctly, you want the data returned by TheUrl to be the return value of the lookForSomething.

Technically, you could do this, with the async option:

function lookForSomething()
{
    var the_data;
    $.ajax({ type: "GET", 
                            url: TheUrl, 
                            dataType: "jsonp", 
                            async : false,
                            success: function(result) { the_data = result; } 
                            });
    return the_data;
}

I strongly urge you not to do this. It's un-Javascript-like and it will lock up the user's browser while it's running. Much better to pass in a callback to the function and invoke it from success.

Upvotes: 1

Related Questions