Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: JavaScript
Expertise: Beginner
May 18, 2004

Execute Form Processing Code Without the BODY Tag

I've had two instances recently where I had to execute some form processing code once the page load event was fired. However, I didn't have access to the BODY tag because it was contained in a global header include. Obviously, adding my onload event handler in a global header would throw 'Object does not exist' errors all over the site.

There is the non-standard option of placing your function call in the onload event of an IMG, SCRIPT, or FORM tag, but in my experience, this method is less than perfect or consistent in inconsistently working. A browser can load a form at the bottom of a page before it loads an image at the top of your page. And throwing unfriendly errors, let alone any error, is bad for business. So I came up with a first grade-type solution. Keep trying until you get it right. A perpetual loop that won't throw errors.

Let's say you need to submit a form once a page has loaded and you dont have access to the BODY tag. Create a JavaScript function that consists of a TRY CATCH block, that calls itself when it doesn't work. Basically a recursive function:


function submitOnFormLoad()
	{
	try
		{
		document.myForm.submit();
		}
	catch(e)
		{
		submitOnFormLoad();
		}
	}
submitOnFormLoad();
After and outside of the function block, call the function. It tries to submit the form. If it doesn't work for any reason, it catches the error. Once it catches an error, its instructions are to call itself, which starts the process all over.

Between the recursivness and catch functionality, you have a perpetual loop that won't throw errors. Be careful how you use this. As simple as it seems, in the wrong logical conditions, it could run forever and hang your client's browser.

Michael Sanchez
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap