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

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
jamescorryAsked:
Who is Participating?
 
OnthraxConnect With a Mentor Commented:
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
 
OnthraxCommented:
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
 
OnthraxCommented:
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
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
OnthraxCommented:
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
 
jamescorryAuthor Commented:
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
 
jamescorryAuthor Commented:
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
 
OnthraxCommented:
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
 
jamescorryAuthor Commented:
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
 
jamescorryAuthor Commented:
more points!
0
 
OnthraxCommented:
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
 
jamescorryAuthor Commented:
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
 
OnthraxCommented:
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
 
jamescorryAuthor Commented:
Thanks :)
0
 
jamescorryAuthor Commented:
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
 
OnthraxCommented:
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
 
jamescorryAuthor Commented:
I don't even get an error, just nothing happens :-s
0
 
OnthraxCommented:
It'll take some time but I'll do my best to figure it out.
0
 
jamescorryAuthor Commented:
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
 
OnthraxCommented:
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
 
jamescorryAuthor Commented:
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
 
OnthraxCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.