views:

372

answers:

5

I have inherited an ASP.net codebase and I have very limited ASP.net skills. I am struggling to understand why something works and also why it only works in IE.

The following code appears in a page :-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="map.aspx.cs" Inherits="Romtrac.auth_map" Culture="auto" UICulture="auto" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>
        <% = Resources.Resource.map %>
    </title>
</head>
<body>    
    <form id="adminlw_map_form" action="<%=geturl()%>" method="post"  >

    <% = Resources.Resource.loading %>...
    <textarea name="xml" id="xml" runat="server" style="display:none" cols="1" rows="1"></textarea>
    </form>
    <script language="javascript" type="text/javascript" >
      //submit main form immediately
        document.getElementById('adminlw_map_form').submit();
    </script>
</body>
</html>

This code runs fine in ASP.net. The form is automatically submitted and the page returned is rendered correctly within an Iframe. My question is;

1) Does the javascript within the body just get executed when it is encountered? Is this good practice or should it be executed in response to an event?

2) Why does this not work in other browsers?

+3  A: 

1) Yes, No. jQuery does it best with it's $(document).ready() function, but you should wait for the page to finish loading before running Javascript.

2) Do #1 and you won't need to worry about this. However I'll leave the floor open to someone with a better answer.

Mike Robinson
A: 

Same as Mike Robinson's answer but surely you can just use <body onload="myfunction();">?

Lucas Jones
+4  A: 
  1. Yes
  2. The javascript is being executed before the browser has fully rendered the page. In this case, the form has not been rendered and is not accessible via the DOM.

The execution needs to happen after the DOM is fully loaded by the browser and can be implemented by encapsulating the call within a function and calling that function via the the onload event of the body or by using a javascript library like jquery to hook into the load event of the page.

catalpa
+1  A: 

Some browsers prevent the submission of a form without user interaction in the page's load 9it's a security risk). I've had this issue a number of times in the past. I would combine the page's load, with a window.setTimeout of say 100ms.

<body onload="window.setTimeout( document.getElementById('adminlw_map_form').submit, 100)">
....
Tracker1
+1  A: 

Remember when using JavaScript to keep it unobtrusive. There are still people out there who have JS switched off and your page should not really on it. It should serve as an enhancement.

John Polling