2

Can anyone tell me about how to poll to webMethod on specific interval using Javascript/JQuery ? I tried setInterval & setTimeOut but non of them is working for me. My application generates reports on user's request. since the report generation is taking 10-15 minutes I dont want to block UI thread so I create a reportID on button click from javascript and using _dopostback to call button click event and pass the reportID to it. C# button click event calls generate_report() function using Delegate/BeginInvoke and now I want to poll to WebMethod I have created inorder to get the report... here is a code snippet..

 $("#btn1").click(function () {
     var ReportID = generateReportID();
     __doPostBack("<%= btnGenerate.UniqueID %>", ReportID);
     IntervalID = setInterval(function () { Poll(ReportID); }, 30000);
 });

 function Poll(id) {
     $.ajax({
         type: "POST",
         url: "Default.aspx/WebMethod",
         data: "{'ReportID','" + id + "'}",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (response) {
                    // Check if report is ready 
                    // If not poll again after 30 secs
                    // If report is ready Get the Report and clearInterval
         },
         failure: function (error) {
         }
     });
 };

 [WebMethod]
 public static string WebMethod(string ReportID)
 {
     if (ResultSet.ContainsKey(int.Parse(ReportID)))
     {
         return "Ready";
     }
     else
     {
         return "NotReady";
     }
  }

So On button click how do I start poll to this web method after every 30 secs till report is "Ready" and clear the interval after once its ready. ??

Mithun Ganatra
  • 453
  • 4
  • 21

2 Answers2

2

SetInterval was working fine, PostBack was the culprit.... subsequent postbacks i.e. button clicks would kill the previous setintervals.... so now I pass all the ReportIDs to codebehind on button click function and setIntevals using client script

Page.ClientScript.RegisterStartupScript(typeof(Page), "test" + UniqueID, "setInterval(function () { Poll(ReportID); }, 30000);", true);

alternative to send ReportIDs to code behind functions and looping through and setting interval foreach ReportIDs using client script, one can also save ReportIDs in localStorage so that its available in subsequent postbacks.

NOTE : Thanks a tonn for your help @Krzysztof Safjanowski

Mithun Ganatra
  • 453
  • 4
  • 21
0

Use SetTimeout to call itself recursively, until you have the result you want.

Ex:

function initPoll()
{
    setTimeout(pollWebServer(), 30000);
}    
function pollWebServer()
{
     if(!checkResult())
         setTimeout(pollWebServer(), 30000);
}    
function checkResult()
{
    //Do some work to check result that you are looking for
    //This is where you would check your Web Method using jQuery
    return false;
}
Chris Fremgen
  • 4,649
  • 1
  • 26
  • 26