I have an <asp:Button ID="btnExport"> control inside of an UpdatePanel. When that button is clicked, I’d like it to immediately execute a Javascript function (it’s a polling function that will run continuously while the UpdatePanel is doing its postback). How can I do this?
I’ve tried this:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);
function pageLoaded(sender, args) {
$(".btnExport").click(function (e) {
timer = window.setInterval(pollStatus, 1000);//
});
}
That works, but then it doesn’t execute the btnExport event handler. Everything I try either executes the event handler and not the polling function or vice-versa. What I’m really looking for is a way to do this:
1) Click on the Export button.
2) Set a timer to do a polling event (javascript function) every second.
3) Execute the event handler for the Export button.
4) Once the postback is done, clear the timer.
Anyone have any suggestions as to the best way to accomplish this?
Here’s some sample code. This is from a small sample application I wrote just to illustrate the point, my actual app is a bit too complex to post here.
DEFAULT.ASPX
<asp:ScriptManager runat="server" ID="ScriptManager1"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<asp:Button runat="server" ID="btnExport" Text="Begin Export" OnClick="btnExport_Click" ClientIDMode="Static" /><div id="message"></div>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
var timer;
function pollStatus() {
$.ajax({
type: "POST",
url: "<%= Page.ResolveUrl("~/Default.aspx/PollStatus") %>",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#message").html(response.d);
}
});
}
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);
function pageLoaded(sender, args) {
$("#btnExport").click(function (e) {
timer = window.setInterval(pollStatus, 50);
});
}
</script>
DEFAULT.ASPX.CS
protected void btnExport_Click(object sender, EventArgs e)
{
for (int i = 1; i <= 10000000; i++ )
{
Session["PollStatus"] = i;
}
}
[WebMethod]
public static string PollStatus()
{
return HttpContext.Current.Session["PollStatus"] != null ? HttpContext.Current.Session["PollStatus"].ToString() : "No result";
}
I do not see a css class specified here:
However, your selector is trying to get the object(s) by class:
So, you should either set the CssClass property for your button or change the selector.
UPD:
This code works for me just fine (this is an example, It requires some polishing before prod. usage)
The button’s btnTest_OnClick server-side event handler just does this:
You should see “Test” alerts until the server provides a response back to the client.