views:

26

answers:

1

Hi all,

i have a problem with my code.

function fnFormatDetails ( oTable, nTr )
{
    var aData = oTable.fnGetData( nTr );
    var sOut = "";

    var ajax = $.ajax({
        url: "/wemi/mediaplaner/show?id="+aData[1],
        success:    function(data)  {
            //return data; 
            //return sOut = data;
            //console.log(sOut);
        },
        error:  function()  {
            //alert("Error");
        }
    });

    //document.write(ajax.responseText); //write empty Text
    console.log(ajax); //Real Object all is OK

    //console.log(ajax.responseText); get empty Text
    //alert(ajax.responseText); // get Empty Text
    return sOut;
}

I just need to print the ajaxed text... and as you can see i get only undifined or empty response.

but if i print or alert in success function, all is Ok and i get my response...

+4  A: 

You've discovered the answer already. The ajax call is asynchronous. The code in the "success" handler will be executed when the HTTP request completes. The $.ajax function itself, however, returns immediately after starting the request.

The correct approach is to put the code in the "success" callback. (Or put the call to some other function there.)

Pointy
but if return in success... i have no callback if i print this function... you know what I mean, a need this text in other funtion, but i have to call a function for this. I have to ajaxed text, but my code is a bit wrong...
Fincha
Just call your other function from inside the "success" code. You can't get a "return" value from a $.ajax call - it just doesn't work that way.
Pointy
haw can i let fnFormatDetails() return the ajaxed text?
Fincha
@Fincha you cannot do that when the text comes from an asynchronous AJAX call. It is just absolutely impossible. Instead, you can have that function take *another* function as an argument, so the caller can provide the code that should run when the text arrives in the "success" handler.
Pointy