1

I've found other solution on how to executes a javascript function from code-behind. The problem is that it firing before the page loads, so I can't add logic to it.

if(result)
{
   Page.ClientScript.RegisterClientScriptBlock(typeof(Page), 
                                               "Script", "confirmPwdChange();", true);
}

On the client side

<script>
   confirmPwdChange()
   {
     alert("Password has been successfully changed.");
     //Add more logic here, after user clicks the OK button...
   }
</script>

No Jquery, if possible.

Thanks for helping.

Richard77
  • 20,343
  • 46
  • 150
  • 252
  • 1
    Use `RegisterStartupScript` instead of `RegisterClientScriptBlock`. See http://stackoverflow.com/questions/666519/difference-between-registerstartupscript-and-registerclientscriptblock – VDWWD Oct 31 '16 at 09:11

2 Answers2

2

You might want to include the window.onload in your script file. something like this..

StringBuilder script = new StringBuilder();
script.Append("var existingHandler = window.onload;");
script.Append("window.document.body.onload = function(){ confirmPwdChange(); if (existingHandler){ existingHandler()}}");
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), 
                                           "Script", script.ToString(), true);

this ensure, your change password is called on page load and retains any other existing handlers declared already on the page.

Sreekanth
  • 3,110
  • 10
  • 22
  • I'm getting this error: `Uncaught SyntaxError: Unexpected token <`. – Richard77 Oct 31 '16 at 02:23
  • my bad. corrected the code to not include – Sreekanth Oct 31 '16 at 02:34
  • Now I'm getting the error: `Uncaught ReferenceError: changePassword is not defined at window.onload` – Richard77 Oct 31 '16 at 02:41
  • I gave as a reference method name, replace the changePassword to confirmPwdChange in the server code. updated the snipet – Sreekanth Oct 31 '16 at 02:43
  • It executed but, the same problem as it executed before the page completely loaded. While the alert was displayed, page went blank then loaded. – Richard77 Oct 31 '16 at 02:52
  • this could be apossible reason what the behavior. http://stackoverflow.com/questions/2485244/window-onload-seems-to-trigger-before-the-dom-is-loaded-javascript Modified the code snippet to accomodate the fix. – Sreekanth Oct 31 '16 at 03:46
  • I restarted the computer. Now your code is working. Thanks – Richard77 Oct 31 '16 at 16:47
1

I think you're looking for PageRequestManager

List of PageRequestManager events

var prm = Sys.WebForms.PageRequestManager.getInstance();

// beginRequest: before postback to server
prm.add_beginRequest(BeginRequestHandler);

// endRequest: after postback to server
prm.add_endRequest(EndRequestHandler);

function BeginRequestHandler(sender, args) {
    // do stuff
}

function EndRequestHandler(sender, args) {
    // do stuff
}
AM Douglas
  • 1,873
  • 1
  • 13
  • 17