0

I got this simple part of the code

 if (Request.QueryString["TimeZone"] != null)
 {              
     Response.Write(
         @"<script language='javascript'>alert('TimeZone refreshed, u can now continue');</script>");

     Button1_Click(null, null);
 }

When I run this the application, it will just pass over the alert and run the button click action.

Question

How can I create a delay between those actions? I want give the client the alert and just after that perform the Button1_Click action.

rae1
  • 6,066
  • 4
  • 27
  • 48
user3584562
  • 63
  • 1
  • 11
  • 6
    That Javascript will only be run once the response is returned to the browser and the *browser* executes it, i.e. *after all of your C# code is done*. If you want to fire the click event after an alert, you need to fire the click event with an AJAX request in your Javascript. You need to learn the relationship between server- and client-side code. – Ant P Jun 03 '14 at 14:40

2 Answers2

2

The button click event is ran on the server. The javascript is send to the client and executed there.

There is no way to call the javascript call first, since it first has to create the html and send it to the client.

You could optionally create a call client side by invoking some javascript.

So instead of this in c#:

Button1_Click(null, null);

Do this (code sample from here):

 Response.Write(
     @"<script language='javascript'>var elem = document.getElementById('button1'); elem.onclick.apply(elem);</script>");

Or with using jQuery:

 Response.Write(
     @"<script language='javascript'>$('button1')click();</script>");

This assumes that the button has an id button1. This will probably call ASP.NET again if it has a callback action, so make sure you want to do this.

Otherwise, call a piece of javascript that performs only client side operations, without the need of postbacks, but I don't know if that is possible from your current code sample.

Community
  • 1
  • 1
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

Thanks for the help , big thanks for u @Patrick Hofman ! i already managed a solution , just simple as this

created a java function, and executed there the action click of my button

<script type="text/javascript">


    function myFunction() {


        document.getElementById('Button1').click(); 

    }
</script>

then was just replace this `Button1_Click(null, null); for this in order to run this

if (Request.QueryString["TimeZone"] != null)
            {
                Response.Write(@"<script language='javascript'>alert('TimeZone refreshed, u can now continue');</script>");
                Page.ClientScript.RegisterStartupScript(this.GetType(), "myFunction", "myFunction()", true);



            }
user3584562
  • 63
  • 1
  • 11