23

I've seen lots of questions and solutions to problems like this but nothing has worked for me. I have this:

function() {
    $("#bdiv").load("bosses.php #icc10n",function(){
        return $("#bdiv").html();
    });
}

But it's not working. To clarify, I want to load content into #bdiv and then return the contents of #bdiv. But it seems that $("#bdiv").html() is being returned before the content is loaded even though I've put it in a callback function.

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
Dan
  • 357
  • 1
  • 3
  • 8

3 Answers3

52
$("#bdiv").load("bosses.php #icc10n",function(data){
    // use the data param
    // e.g. $(data).find('#icc10n')
});
Petah
  • 45,477
  • 28
  • 157
  • 213
1

as far as I know you cannot make a return statement in the callback function of a $.ajax(), $.post(), $.get(), etc.. method. You could, however, store the 'data' value in a variable declared outside the function, and then set the value of that variable when the callback function executes. And there is a variety of other options.

Danny Bullis
  • 3,043
  • 2
  • 29
  • 35
0

You can't do that.

AJAX is asynchronous, meaning that your function will return before the server sends a response.
You need to pass the value to your caller using a callback, the way $.load does.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • @Onkelborg: He needs to return the value by making his own callback. – SLaks Oct 20 '10 at 00:57
  • The .html() is evaluated when the function is declared, and not when it's called, right? – salezica Oct 20 '10 at 01:03
  • @Santiago: Totally wrong. The `return` statement is returning from the inner callback method; this return value is ignored by jQuery. The outer function returns immediately. – SLaks Oct 20 '10 at 02:25
  • Call me slow, but I still don't really understand how it's done and why the above approach doesn't work. I know this is not my question, but would you mind adding an example and/or explaining a bit further? This bit my curiosity! – salezica Oct 20 '10 at 02:59