Solved

How to call a JavaScript function from within _Click function

Posted on 2007-03-21
41
778 Views
Last Modified: 2008-03-06
I'm not a Javascript Guru and in fact try to stay away from it other than the Atlas framework.

So if I have this
<!--
      function reload()
      {
            window.opener.top.MainFrame.MessageSubjectFrame.location.reload();
            window.opener.top.MainFrame.document.getElementById("MessageFrame").style.display ='None';
      }
//-->
      </script>

how do I call the reload function in my button's onclick function
    Protected Sub btnAccept_Click(ByVal sender As Object, ByVal e As EventArgs)
        call the reload function in here
    End Sub

0
Comment
Question by:dba123
  • 25
  • 9
  • 7
41 Comments
 
LVL 5

Expert Comment

by:jef06
ID: 18764472
If you are using Atlas, then you are using .Net 2.0

<asp:Button ID="cmdOne" Text="ASP.NET 2.0 Button" runat="server" OnClientClick="alert('Client side javaScript alert() function called')" />
0
 
LVL 43

Accepted Solution

by:
TimCottee earned 125 total points
ID: 18764484
You cannot do it server-side as this is a client-side script. What you can do is add it to the client-side click event:

For asp.net 1.1:  in page_load use:

btnAccept.Attributes.Add("onclick","reload();")

For asp.net 2.0: set the .onclientclick property to "reload();"
0
 
LVL 1

Author Comment

by:dba123
ID: 18764490
ok, but I still want to call my OnClick function...so then yo'ure saying just add the OnClientClick in addition to Onclick or is there a way to d something like this
OnClick="btnAccept_Click; return reload();")"

let me try my hack and see if it works.

0
 
LVL 5

Expert Comment

by:jef06
ID: 18764503
<asp:Button ID="cmdOne" Text="ASP.NET 2.0 Button" runat="server" OnClick="btnAccept_Click" OnClientClick="alert('Client side javaScript alert() function called')" />
0
 
LVL 43

Expert Comment

by:TimCottee
ID: 18764533
The two events are independent. If you call an onclientclick, it will execute and then the onclick event handler will take over after that. Generally this is not a good idea if you are refreshing the same page, however it looks like you are refreshing a parent so that is perfectly ok.
0
 
LVL 1

Author Comment

by:dba123
ID: 18764567
Do I need to do it this way or is this just another way

strScript = "reload();"
RegisterStartupScript(strScript)
0
 
LVL 1

Author Comment

by:dba123
ID: 18764576
by the way, this call will be made from a pop-up page I'm working on (I hate pop-ups, but not my decision at the momen).  So when the user clicks accept, I want the window to close and then to refresh the parent page is what I'm trying to get working
0
 
LVL 43

Expert Comment

by:TimCottee
ID: 18764602
Does the popup need to close after the postback or do you not need the postback? If you want it to close after the postback then you need to add a bit of script in your btnAccept_Click() event handler:

Response.Clear()
Response.Write("<script language=javascript>self.close();</script>")
Response.End()

This will effectively write a single line of script to the window when it is rendered after the postback which will cause it to close.
0
 
LVL 1

Author Comment

by:dba123
ID: 18764616
Ok I guess let me tell you what I tried now
I changed the funciton first off

      function reload()
      {
            window.opener.top.MessageSubjectFrame.location.reload();
            window.close();
      }

ok, now I have this

    Protected Sub btnAccept_Click(ByVal sender As Object, ByVal e As EventArgs)
        vcUser.UpdateEBookPolicyDate()
        btnAccept.Attributes.Add("onclick", "reload();")
    End Sub

So, when I click on the accept button, I think I'm refreshing the pop-up page and not the parent (the one I navigated from)

How can you tell if the reload worked or was called other than debugging. I assume look at the source view in IE.
0
 
LVL 5

Expert Comment

by:jef06
ID: 18764621
carefull if you do a reload of the parent it might open your popup again, you might want to use location instead of reload on the window.parent.location.href= window.parent.location.href;
0
 
LVL 5

Expert Comment

by:jef06
ID: 18764625
this btnAccept.Attributes.Add("onclick", "reload();") need to be done on the page_load
0
 
LVL 1

Author Comment

by:dba123
ID: 18764627
I don't really need the postback
0
 
LVL 1

Author Comment

by:dba123
ID: 18764632
why on the page load if I only want this to happen when invoked by the clicking of the Accept button?
0
 
LVL 5

Expert Comment

by:jef06
ID: 18764636
<script language="C#" runat="server">
  protected  void Page_Load(object sender, EventArgs e){
    //Set the button's client-side onmouseover event
    btnClick.Attributes.Add("onClick", "alert('Ouch, you clicked me!');");
  }
</script>

<form runat="server">
  <asp:button runat="server" Text="Click Me!" id="btnClick" />
</form>
0
 
LVL 43

Expert Comment

by:TimCottee
ID: 18764663
After the postback you mean. Ok, then that means that you should use the same technique as for the close() I just showed you to emit the reload on the btnAccept_Click.

You cannot use the attributes.add method as this just adds the event handler to the button click, it doesn't actually execute it until that button is clicked. You need to use response.write or page.clientscript.registerstartupscript to emit the relevant javascript. Now it is likely in fact that you won't even have this function if you use response.clear() so you may be better off emitting the whole bit of script as a one-off:

    Protected Sub btnAccept_Click(ByVal sender As Object, ByVal e As EventArgs)
        vcUser.UpdateEBookPolicyDate()
        Response.Clear()
        Response.Write("<script language=javascript>window.opener.top.MessageSubjectFrame.location.reload(); window.close();</script>")
        Response.End()
    End Sub
0
 
LVL 1

Author Comment

by:dba123
ID: 18764694
I guess I'm not sure if I need or don't need the postback....I'm not doing anything with session state, cookies, etc. so I assume I don't need to worry about it.
0
 
LVL 5

Expert Comment

by:jef06
ID: 18764698
You should never use Response.Write to send client side script.
0
 
LVL 1

Author Comment

by:dba123
ID: 18764702
>>>You should never use Response.Write to send client side script.

reason?
0
 
LVL 43

Expert Comment

by:TimCottee
ID: 18764707
Probably not jef06 though it is effective in this kind of situation. Of course you can use the registerstartupscript/registerclientscriptblock and these will have the same effect.
0
 
LVL 1

Author Comment

by:dba123
ID: 18764711
Ok, again, here's what I have but it's not working.  I want this pop-up to close then refresh the parent

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        panAgreement.Visible = True
        btnAccept.Attributes.Add("onclick", "reload();")
    End Sub

    Protected Sub btnAccept_Click(ByVal sender As Object, ByVal e As EventArgs)
        vcUser.UpdateEBookPolicyDate()
    End Sub

Now, the respnse.write does close it, but Jeff's saying it's not good to use.  However otherwise, the script above without the response.write does nothing as far as my human eye can tell
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 1

Author Comment

by:dba123
ID: 18764720
I guess what's the best way as in coding standards (safety, efficiency, yada, yada) in terms of doing that in ASP.NET on the 2 things I want to happen here.  I don't just want a hack but I'm not sure the best code practice either.
0
 
LVL 1

Author Comment

by:dba123
ID: 18764726
also, my pop-up is an aspx page with a control inside it.  The control contains the Accept button.  Not sure if they makes any difference on our conversations.
0
 
LVL 1

Author Comment

by:dba123
ID: 18764744
what is MessageSubjectFrame, the name of the frame you want to apply this on correct?
0
 
LVL 5

Expert Comment

by:jef06
ID: 18764752
you have no control of the response object like in asp, it means that you migth send client side script which are either not in the html tag or any where in the page, also using end will stop the response will the page is not complete. use register or attribute but not response
0
 
LVL 1

Author Comment

by:dba123
ID: 18764763
>>carefull if you do a reload of the parent it might open your popup again

shouldn't.  Cause here's the sequence of what I'm doing

1) I click on this link in an aspx page of ours.  This aspx page is in an iframe or something

<asp:HyperLink ID="HyperLink1" ForeColor="black" NavigateUrl="JavaScript: void(0);"  OnClick="javascript:var v=window.open('/controls/EBookPolicy.aspx', 'eBookPolicy', 'top=5,left=5,width=780,height=300,resizable=1,channelmode=0,directories=0,fullscreen=0,location=0,menubar=0,scrollbars=0,status=0,titlebar=0,toolbar=0');" runat="server"><b>HERE</b></asp:HyperLink>

2) Pop-Up comes up. The Pop-Up page is another aspx and it contains a registered control that contains the acept button
0
 
LVL 43

Assisted Solution

by:TimCottee
TimCottee earned 125 total points
ID: 18764787
No, it doesn't make a difference. The thing with attributes.add is that you are adding client-side attributes of an element from the server-side. So you can tailor client-side events such as the onclick, onmouseover etc based on server-side held values. This allows you to make dynamic tooltips for onmouseover for example. However this method does not actually cause these javascript snippets to run. It simply allows them to be run when the appropriate trigger occurs, be that a click, roll-over or keypress.

Using response.write to emit the relevant script may not be perfect but does do the job. You can achieve the same effect using the page.clientscript.registerstartupscript() method. Though you would probably be as well to use response.clear() first.
0
 
LVL 1

Author Comment

by:dba123
ID: 18764800
Ok, but I don't get why this isn't wroking also below.  Seems to me that this adds it to the button and then when clicked, the reload is called. Maybe it is working but just not refreshing the right page.  I think it's refreshing my pop-up page instead as I do see it flash.  Also my current reload function is not closing the window so I'll try to add the self.close into my actual javascript reload function right after the refresh call

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        panAgreement.Visible = True
        btnAccept.Attributes.Add("onclick", "reload();")
    End Sub

    Protected Sub btnAccept_Click(ByVal sender As Object, ByVal e As EventArgs)
        vcUser.UpdateEBookPolicyDate()
    End Sub
0
 
LVL 5

Expert Comment

by:jef06
ID: 18764830
If you open the popup with a registerstartupscript the page might only reload the page from the cache and the re popup your page, also using Reload might not post pack your page on the server. add at the end of location a random number
0
 
LVL 1

Author Comment

by:dba123
ID: 18764997
So here is what  "seems"t o be working, just that I need some delay window.setTimeout  or something before it refreshes the parent page but not sure what I should put in for the first param of selfTimeout

      function reload()
      {
      window.opener.location.reload();
      self.close();
      }

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        panAgreement.Visible = True
        btnAccept.Attributes.Add("onclick", "reload();")
    End Sub

so that works but

1) How do I know I"m targeting the parent aspx (the one I came from before the pop-up)
2) How do I add that delay so that I bring the user back to that page after the DB transaction is done

0
 
LVL 1

Author Comment

by:dba123
ID: 18765022
so I took out some stuff from before which was

    window.opener.top.MainFrame.MessageSubjectFrame.location.reload

took out the MinFrame.MessageSubjectFrame part and it seems to work however I feel I should be targeting the right frame so I need to figure that out.
0
 
LVL 43

Expert Comment

by:TimCottee
ID: 18765072
You are targetting the correct parent window, if that parent has move to a different page, it will be reloaded. This is because the window.opener refers to the window not the document object.

To add the delay you can use:

setTimeout('window.opener.location.reload();window.close();',1000);

Which will give a one second delay before those two script statements are run.
0
 
LVL 1

Author Comment

by:dba123
ID: 18765160
I tried this, but now it doesn't do a thing
      function reload()
      {
                         setTimeout('window.opener.location.reload();window.close();',1000
      }
Thi s is what I had that worked

      function reload()
      {
            window.opener.location.reload();
            self.close();
      }
0
 
LVL 1

Author Comment

by:dba123
ID: 18765174
0
 
LVL 1

Author Comment

by:dba123
ID: 18765216
My entire argument against Javascript scripting inside n aspx is that now .NET controls can create the client-side JavaScript.  When I see an aspx page with a ton of JavaScript functions in it, it makes me think that the people who coded the .NET are still thinking in classic asp terms am I wrong?
0
 
LVL 5

Expert Comment

by:jef06
ID: 18765231
I did an entire site using asp.Net custom made Ajax framework, and the feel for the user is so much better :)
0
 
LVL 1

Author Comment

by:dba123
ID: 18765252
I mean should it be this way?  I tried this but I assume that I don't need the additional lines after Set Timeout

      function reload()
      {
          setTimeout('window.opener.location.reload();self.close();',1000)
            window.opener.location.reload();
            self.close();
      }
0
 
LVL 1

Author Comment

by:dba123
ID: 18765268
>>I did an entire site using asp.Net custom made Ajax framework, and the feel for the user is so much better :)

No, I love Ajax, dont' get me wrong.  I guess then I jus tdon't like to see a ton of Javascript code ni an aspx.  Not having used Atlas yet, I assume though that you're using .NET client-side type controls so you don't see a mess of JavaScript defined in your aspx?
0
 
LVL 1

Author Comment

by:dba123
ID: 18765275
the whole concept behind Javascript  driving Ajax is fine, I just don't like to see a ton of JavaScript in an aspx and thinking the framework for Atlas is probably much cleaner in that you ar eusing more organized controls and standards
0
 
LVL 1

Author Comment

by:dba123
ID: 18765329
well, I'm working on figuring out why this is not working

      function reload()
      {
          setTimeout('window.opener.location.reload();self.close();',1000)
            window.opener.location.reload();
            self.close();
      }

it's closing the window but now I don't get a refresh and it's closing it immediately, the delay isn't working.
0
 
LVL 1

Author Comment

by:dba123
ID: 18765359
also tried this, but then nothing happens period

        btnAccept.Attributes.Add("onclick", "setTimeout('reloadParent()';,2000)")
0
 
LVL 1

Author Comment

by:dba123
ID: 18765369
btnAccept.Attributes.Add("onclick", "setTimeout('reloadParent()';,2000

function reloadParent()
      {
            window.opener.location.reload();
            self.close();
      }
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
In this Article, I will provide a few tips in problem and solution manner. Opening an ASPX page in Visual studio 2003 is very slow. To make it fast, please do follow below steps:   Open the Solution/Project. Right click the ASPX file to b…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now