0

Given the following code:

    $.get("somepage.html", function (data) {
        $("#someID").html(data);
    });

data goes out of scope immediately. It goes so far out of scope that it nukes any references to it so that

function jqAjaxGet(view){
    $.get(view, function (data) {
        return data;
    });
}

returns undefined and

var globalRetVal = "TestVal";
function jqAjaxGet(view){
    $.get(view, function (data) {
        globalRetVal = data;
    });
    return globalRetVal;
}

returns "TestVal". I've run into this in the past and it's always been a matter of me abusing some other way of doing what I should have been doing but this time, I just plainly want to get the contents of a file and plop it into a container (similar to rendering a partial). I've found that a solution to this is to pass in a target ID so that I dump data into that container immediately but I'd like to simplify the method signature because, hey, someday I might just want the contents of that thing for calculation instead of immediately displaying it.

What do I need to do to keep a reference or, better yet, return the value in data because storing it in a global isn't working?

user4593252
  • 3,496
  • 6
  • 29
  • 55
  • 1
    $.get is asynchronous. – Mike Loffland Mar 20 '15 at 17:35
  • In your second example, the function `jqAjaxGet` doesn't have a `return` statement, hence its return value is `undefined`. That has nothing to do with the scope of `data`, that's how functions work in JS. Nested function declarations don't impact the outer function. Do you really expect `function foo() { function bar() { return 42; } }; foo();` to return `42`? – Felix Kling Mar 20 '15 at 17:37
  • Good catch on that. Normally something I'd catch but hey, you win some, you lose some. All the same, the problem is asynchonicity. I'm trying to figure out how to thank the person who tagged this as duplicate... – user4593252 Mar 20 '15 at 17:39

0 Answers0