开发者

How to set ajax returned value as a variable

开发者 https://www.devze.com 2023-02-14 23:27 出处:网络
I have the following ajax call which executes successfully: function fnFormatDetails ( oTable, nTr ) { var aData = oTable.fnGetData( nTr );

I have the following ajax call which executes successfully:

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

            var memberid = 'memberid='+ aData[6];

            $.ajax({
                type: "POST",
                url: "shout.php",
                data: memberid,
                success: function(html) {
                    //$("#shout").html(html);   
                    var sOut = html.returned_val;
                }
            });

            return sOut;
        }

If I remove the commented out line ($("shout").html(html) and use a div on my page, the results display fine. However,开发者_StackOverflow there is a second function which would use the HTML results from sOut and display accordingly in the proper position.

The PHP file in shout.php simply 'echos' HTML to the page (which is then returned and displayed accordingly.

I am unfortunately unable to set the variable sOut currently based on the results of my ajax call. What am I missing?


If you'd like your function to return what returns from the AJAX call, you need to make the call synchronously. Also, this is assuming the result of "shout.php" is plaintext. If it's JSON or otherwise, you need to set the dataType property in your call to $.ajax.

function fnFormatDetails ( oTable, nTr ) {
    var aData = oTable.fnGetData( nTr );
    var memberid = 'memberid='+ aData[6];

    var result;

    $.ajax({
        type: "POST",
        url: "shout.php",
        data: memberid,
        async: false,
        success: function(data) {
            result = data;
        }
    });

    return result;
}


First of all you are defining sOut within a success callback method and therefore it would not be available to fnFormatDetails.

Secondly by default $.ajax works in async mode, therefore whenever "return sOut" is called, the success callback would have not executed !

I would suggest you to call some method from the success which would do the process based on the html.returned_val, or you can pass async:false in $.ajax to make that call synchronized.


thank you @Matt Huggins

async: false

this small code change, fixed the issue i was having since morning. :)

0

精彩评论

暂无评论...
验证码 换一张
取 消