0

Sorry, but I am new to jQuery so this may seem like a dumb question.

I have a generic function that will call a $.get to retrieve some data from a URL and I then want to assign to a variable, not a control.

Here's my function, it has been simplified to clear out the "noise"...

function LoadFromURL(url) {
    var response = "";
    $("textarea#dump").val("url=" + url);   // Shows the URL, no problem

    $.get(url, "", function (data) {
        response = data;
        $("textarea#dump").val(response);   // Shows the data, no problem
    });

    $("textarea#dump").val(response);   // Shows NOTHING!
    return (response);
}

The problem is that the response value quite happily assigns inside the callback function, but when it gets to the return (response) then the variable is empty.

Chris Hammond
  • 2,064
  • 5
  • 27
  • 53
  • Following Quentin's link shows just how little I know about jQuery/Ajax... Having read the linked question, I now understand that I need to refactor the code for asynchronous operation. – Chris Hammond May 14 '14 at 07:42

1 Answers1

0

The Shows NOTHING line is fired too soon to be useful. You must start from the callback function and go from there. You could call a method from the callback.

Call it like this:

var cb = function(data) {
  $("textarea#dump").val(data);  
}
LoadFromUrl("someUrl", cb);

or inline like this:

LoadFromUrl("someUrl", function(data) {
   $("textarea#dump").val(data);  
});

Change your method like this:

function LoadFromURL(url, cb) {
  $("textarea#dump").val("url=" + url);   // Shows the URL, no problem


  $.get(url, "", function (data) {
     cb(data);  //<-- call the CallBack method
  });

}

This is more the behavior of javascript than jQuery, callbacks are a way of life in js.

T McKeown
  • 12,971
  • 1
  • 25
  • 32