[RESOLVED]When using JQuery with JSON calling a webmethod, what is the best way of handling timing for the client side to wait for data returned from the server?

I am looking in general at the best way to detect when a script on the client side calling a webmethod in codebehind has received the data on the client side.

I have to use an alert to stop the script, and in doing so it works because of creating enough pause.  I have created a timer, but I would rather have something detect it has returned

function getData() {
var pal = [];
var request = $.ajax({ type: 'POST',
url: '/App_Pages/index.aspx/getData',
data: "{MyID: '1'}", contentType: "application/json; charset=utf-8", dataType: "json", }); request.done(function (data) { // alert('done'); // alert(data.d); var MyData = data.d; for (var i = 0; i < MyData.length - 1; i++) { pal.push(MyData[i]); } }); request.fail(function (jqXHR, textStatus) { alert("Request failed: " + textStatus); });
alert('pause'); alert(pal[3]);
}

If I have the alert(‘pause’); uncommented, I get a value for alert(pal[3]);

If I comment out the alert("pause"); I get an undefined value for alert(pal[3]);

I know it is a timing issue but what is the best way to sense that the data has been returned?

What is happening is that your ajax call is asynchronous. Your getData() function will execute line by line. So your essentially calling console.log(pal[3]) before the data has returned from the server. Your request.done() is the callback. This fires after
the data has been received from the server. To Accomplish what you want you need to move the alert into the call back:

request.done(function (data) {
                //  alert('done');
               // alert(data.d);
                var MyData = data.d;
                for (var i = 0; i < MyData.length - 1; i++) {
                    pal.push(MyData[i]);

} alert('pause'); alert(pal[3]); });

hope it helps!

Leave a Reply