Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to change <script> block inside updatepanel on every updatepanel refresh?

Posted on 2008-10-03
21
Medium Priority
?
1,355 Views
Last Modified: 2012-06-21
Hi,

I need to use javascript to add points on to map (i can do this) but then I need to get new co-ordinates (from a database) to plot on the map on an updatepanel refresh. What I've got so far is the updatepanel firing every 60 seconds and retrieving up-to-date co-ordinates from a sql database. This works fine. I now have the problem of generating new javascript with either just the new co-ordinates being sent to the existing javscript functions to run, or a new <script> block where I can force the map applet to replot the new points. I'm finding this hard from the updatepanel though.

I've been experimenting with using script RegisterClientScriptBlock and RegisterStartupScript but both don't seem to run/fire when I've added them. Should I be able to use these methods to make new <script> blocks execute on an updatepanel refresh? Or indeed pass my new co-ordinates on to an existing function.

Any help would be much appreciated,

Cheers,
James
0
Comment
Question by:jamescorry
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 11
  • 10
21 Comments
 
LVL 13

Expert Comment

by:Onthrax
ID: 22632134
I assume you have a javascript function that gets called to set these points. What you need is to re-call this function each time an updatepanel refreshes.

There is a little (undocumented?) trick that allows you to do this.

Hope this helps :)

                        Dim UpdatePanelFix As New StringBuilder
                        UpdatePanelFix.AppendLine(AddScriptBlock(ScriptBlockStates.Start))
                        UpdatePanelFix.AppendLine(AddTabs(1) & "Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);")
                        UpdatePanelFix.AppendLine(AddTabs(1) & "Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);")
                        UpdatePanelFix.AppendLine(AddNewLines(1))
                        UpdatePanelFix.AppendLine(AddTabs(1) & "function BeginRequestHandler(sender, args)")
                        UpdatePanelFix.AppendLine(AddTabs(1) & "{")
                        UpdatePanelFix.AppendLine(AddTabs(2) & "var elem = args.get_postBackElement();")
                        UpdatePanelFix.AppendLine(AddTabs(2) & "!!!!!!!!!!!!!!!!!!!!!!!YOUR FUNCTION HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!;")
                        UpdatePanelFix.AppendLine(AddTabs(1) & "}")
                        UpdatePanelFix.AppendLine(AddNewLines(1))
                        UpdatePanelFix.AppendLine(AddTabs(1) & "function EndRequestHandler(sender, args)")
                        UpdatePanelFix.AppendLine(AddTabs(1) & "{")
                        UpdatePanelFix.AppendLine(AddTabs(2) & "!!!!!!!!!!!!!!!!!!!!!!!YOUR FUNCTION HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!;")
                        UpdatePanelFix.AppendLine(AddTabs(1) & "}")
                        UpdatePanelFix.AppendLine(AddScriptBlock(ScriptBlockStates.End))
 
                        Page.ClientScript.RegisterStartupScript(Page.GetType, "UpdatePanelFix", UpdatePanelFix.ToString() & vbCrLf)

Open in new window

0
 
LVL 13

Expert Comment

by:Onthrax
ID: 22632140
Forgot to remove my Addtabs function.

Corrected one below.

Dim UpdatePanelFix As New StringBuilder
UpdatePanelFix.AppendLine(AddScriptBlock(ScriptBlockStates.Start))
UpdatePanelFix.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);")
UpdatePanelFix.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);")
UpdatePanelFix.AppendLine(AddNewLines(1))
UpdatePanelFix.AppendLine("function BeginRequestHandler(sender, args)")
UpdatePanelFix.AppendLine("{")
UpdatePanelFix.AppendLine("var elem = args.get_postBackElement();")
UpdatePanelFix.AppendLine("!!!!!!!!!!!!!!!!!!!!!!!YOUR FUNCTION HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!;")
UpdatePanelFix.AppendLine("}")
UpdatePanelFix.AppendLine(AddNewLines(1))
UpdatePanelFix.AppendLine("function EndRequestHandler(sender, args)")
UpdatePanelFix.AppendLine("{")
UpdatePanelFix.AppendLine("!!!!!!!!!!!!!!!!!!!!!!!YOUR FUNCTION HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!;")
UpdatePanelFix.AppendLine("}")
UpdatePanelFix.AppendLine(AddScriptBlock(ScriptBlockStates.End))
 
Page.ClientScript.RegisterStartupScript(Page.GetType, "UpdatePanelFix", UpdatePanelFix.ToString() & vbCrLf)

Open in new window

0
 
LVL 13

Expert Comment

by:Onthrax
ID: 22632146
damn forgot to remove even more haha..

this should be the one..

Dim UpdatePanelFix As New StringBuilder
UpdatePanelFix.AppendLine("<script language=""javascript"" type=""text/javascript"">")
UpdatePanelFix.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);")
UpdatePanelFix.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);")
UpdatePanelFix.AppendLine("function BeginRequestHandler(sender, args)")
UpdatePanelFix.AppendLine("{")
UpdatePanelFix.AppendLine("var elem = args.get_postBackElement();")
UpdatePanelFix.AppendLine("!!!!!!!!!!!!!!!!!!!!!!!YOUR FUNCTION HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!;")
UpdatePanelFix.AppendLine("}")
UpdatePanelFix.AppendLine("function EndRequestHandler(sender, args)")
UpdatePanelFix.AppendLine("{")
UpdatePanelFix.AppendLine("!!!!!!!!!!!!!!!!!!!!!!!YOUR FUNCTION HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!;")
UpdatePanelFix.AppendLine("}")
UpdatePanelFix.AppendLine("</script>")
 
Page.ClientScript.RegisterStartupScript(Page.GetType, "UpdatePanelFix", UpdatePanelFix.ToString() & vbCrLf)

Open in new window

0
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 

Author Comment

by:jamescorry
ID: 22632248
So is that code you've posted just to call and run an existing javascript function? If so , how can I pass it new co-ordinates to update?

 Cheers, James
0
 

Author Comment

by:jamescorry
ID: 22632273
Also I've just tried a simple alert(""Test""); in the "your function here" bits and it still doesn't seem to fire, what am I doing wrong?!
0
 
LVL 13

Expert Comment

by:Onthrax
ID: 22632287
Just like to normally do.

e.g. if you function is called UpdateCoordinates(Param) than you just need to replace !!!!!!!!!!!!!!!!!!!!!!!YOUR FUNCTION HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!! with UpdateCoordinates(Param)

Also if you do not want to use codebehind to enter the javascript to your page, you can also put it in yourself (see code snippet). Remember the code must be on the aspx page that has the updatepanels on it.

Hope this helps

<script language="javascript" type="text/javascript">
 
	Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
	Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
 
	function BeginRequestHandler(sender, args) {
		var elem = args.get_postBackElement();
		UpdateCoordinates(Param);
	}
 
	function EndRequestHandler(sender, args) {
		UpdateCoordinates(Param);
	}
 
</script>

Open in new window

0
 

Author Comment

by:jamescorry
ID: 22632333
Anything I add the "Your Function Here" bit doesn't fire (although I know the timer is firing as the code directly above it does, sets labels ect) , I tried alert(""test"") for example and nothing happened. Does it also matter I'm using masterpages? I have all my functions and script code in the header of my master page and the updatepanel is on a subpage inheriting the masterpage. Can't see it having any effect but I'm not getting any luck so far.

Thanks for your help,

James
0
 

Author Comment

by:jamescorry
ID: 22632351
more points!
0
 
LVL 13

Expert Comment

by:Onthrax
ID: 22632374
Thx for the more points.. but I'm already doing all I can hehe..

I'm not sure about the problem though. The code should work I am using it myself as well. Although I am not using the code in the masterpage but on the page that has the updatepanel on it.
 
 I forgot to mention though you need a scriptmanager present on the page, but I assume that is already the case..

Try to see if above works, if not I'll see if I can whip up a page to show you, perhaps you can adjust to your needs..
 
0
 

Author Comment

by:jamescorry
ID: 22632391
I'm correct in saying that adding alert(""test""); into the "Your function here" should actually fire and popup when the updatepanel is refreshed right? I do have a scriptmanager, as the updatepanel needs it too. It shouldn't matter all the code is in the <head> section either should it? I really can't think what this can be.


Thanks for your continued help,

James
0
 
LVL 13

Expert Comment

by:Onthrax
ID: 22632406
You are correct on all points. I'm having a lunch break in about 30 minutes I'll see if I can whip up an example page for you.. stay tuned :)
0
 

Author Comment

by:jamescorry
ID: 22632423
Thanks :)
0
 

Author Comment

by:jamescorry
ID: 22632575
Bit of an update : Just tried using the code above on a new page with no masterpages ect, just updatepanel , scriptmanager and the updatepanel updating on a button click. The alert(""bleh""); still doesn't fire. :(
0
 
LVL 13

Expert Comment

by:Onthrax
ID: 22632950
I'm having problems getting it to work. It has something to do with Ajax.It cannot find Sys.WebForms.PageRequestManager and therefore does not do anything but spit out a javascript error.

I'm looking into it right now though..
0
 

Author Comment

by:jamescorry
ID: 22632960
I don't even get an error, just nothing happens :-s
0
 
LVL 13

Expert Comment

by:Onthrax
ID: 22633027
It'll take some time but I'll do my best to figure it out.
0
 
LVL 13

Accepted Solution

by:
Onthrax earned 1700 total points
ID: 22633297
I have found the problem. There was a reference missing in web.config

I have created a working example with code from MSDN. See if you can adjust it to your needs.

I can't seem to add the zip file though, I get the following error:

The extension of one or more files in the archive is not in the list of allowed extensions: test4/Default.aspx

So this will be a long thread.
Put this (and nothing more for testing purposes) in your web.config:

<?xml version="1.0"?>
<configuration>

    <system.web>

        <pages>
            <controls>
                <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            </controls>
        </pages>

        <httpHandlers>
            <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
        </httpHandlers>

    </system.web>


</configuration>

Put the snippet in your new default.aspx

There are no other files/code needed to make it work.

Hope this helps.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
 
<%@ Register assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" namespace="System.Web.UI" tagprefix="asp" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<script runat="server">
 
    Protected Sub ProcessClick_Handler(ByVal sender As Object, ByVal e As EventArgs)
        System.Threading.Thread.Sleep(2000)
    End Sub
 
 
 
</script>
 
<html >
<head id="Head1" runat="server">
    <title>PageRequestManager beginRequest Example</title>
    <style type="text/css">
    body {
        font-family: Tahoma;
    }
    div.AlertStyle
    {
      background-color: #FFC080;
      top: 95%;
      left: 1%;
      height: 20px;
      width: 270px;
      position: absolute;
      visibility: hidden;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
 
            <script type="text/javascript" language="javascript">
                Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
                Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
                function BeginRequestHandler(sender, args)
                {
                     var elem = args.get_postBackElement();
                     ActivateAlertDiv('visible', 'AlertDiv', elem.value + ' processing...');
                }
                function EndRequestHandler(sender, args)
                {
                     ActivateAlertDiv('hidden', 'AlertDiv', '');
                }
                function ActivateAlertDiv(visstring, elem, msg)
                {
                     var adiv = $get(elem);
                     adiv.style.visibility = visstring;
                     adiv.innerHTML = msg;       
                     alert("Hello World");
                }
            </script>
 
            <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="Server">
                <ContentTemplate>
                    <asp:Panel ID="Panel1" runat="server" GroupingText="Update Panel">
                        Last update:
                        <%= DateTime.Now.ToString()%>.
                        <br />
                        <asp:Button runat="server" ID="Button1" Text="Process 1" OnClick="ProcessClick_Handler" />
                        <asp:Button runat="server" ID="Button2" Text="Process 2" OnClick="ProcessClick_Handler" />
                    </asp:Panel>
                </ContentTemplate>
            </asp:UpdatePanel>
            <div id="AlertDiv" class="AlertStyle">
            </div>
        </div>
    </form>
</body>
</html>

Open in new window

0
 

Author Comment

by:jamescorry
ID: 22633450
Hi again,

That works yes but i'd need to do the database call in the ProcessClick_handler bit and then i'd be still stuck as to how to pass these co-ordinates to the javascript function. I need get the co-ordinates on updatepanel refresh then either write out a new script block with these co-ordinates as part of it , or call a function and pass down the co-ordinates. Either way I need to fire an existing function or fire a new one i create in the code behind...
0
 
LVL 13

Expert Comment

by:Onthrax
ID: 22633548
That would be easy. Enter a hidden field in your updatepanel and give it an ID. Update this hiddenfield with the results of your database.

Now when the function is called, let's call it UpdateCoordinates again do something like this:

var NewCoordinates = document.getElementById("HiddenField").value
and do the rest of your code next with the NewCoordinates containing your new values.
0
 

Author Comment

by:jamescorry
ID: 22633849
Right I think I can make that work, not sure what all that registerclientscript was about then?! Thanks a lot for your time, you've been very helpful.
0
 
LVL 13

Expert Comment

by:Onthrax
ID: 22634449
Glad I could help.

The registerclientscript part was so you could put it in a function for re-use.

Good luck with implementing it to your needs!
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The most up-to-date version of this article is on my Blog https://iconoun.com/blog/
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

660 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