1

I have button that when clicked, submits records into the database. What im wanting to do is AFTER that button is click it fire a javaScript function. The problem i having is that its always firing before the records are getting inserted. Im new to this clientScript and registering it so please forgive my ignoreance on the subject. I have tried RegisterClientScriptBlock, RegisterStartupScript, and RegisterOnSubmitStatement and not getting the desired result. My code is below. Any help would be very much appreciated.

  ' on load
       If (Not ClientScript.IsClientScriptBlockRegistered("alert")) Then
            Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", 
            "alertHello()", True)
        End If

   'button clicked
    Button1.Attributes.Add("onclick", " return alertHello();")
JTeagle
  • 2,196
  • 14
  • 15
Will
  • 1,084
  • 5
  • 20
  • 42

2 Answers2

0

Try using

System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=""JavaScript"">alert("alertHello()")</SCRIPT>")
Gage
  • 7,365
  • 9
  • 47
  • 77
0

Is sounds like the event is firing because that's what onclick does; it calls the onclick event handler, and then if the event is not cancelled, does whatever the button would have done otherwise, which, in WebForms, posts back to the server. Certainly the records can't be inserted until after the data has been sent to the server.

If the whole page is refreshed upon the button click, then you'll have to arrange for the new page to run your javascript. @Gage's answer shows one way to do that. Remember that this is not in the page with the button, it's in the page you get after you click the button.

You could also submit the request to add the records via ajax, and then the page does not refresh. Instead, you make an ajax request, and set a callback, which is a javascript routine that runs when the ajax request completes. You may find this SO thread helpful for more on this: Using jQuery for AJAX with ASP.NET Webforms

Community
  • 1
  • 1
Joshua Frank
  • 13,120
  • 11
  • 46
  • 95