Monday, February 26, 2007

AJAX Safe HTML Forms

Whenever you create a form on a HTML page it's easy to make it AJAX safe. All you have to do is call your ajax form submission code in the forms onsubmit event and specify the standard postback address in case the ajax fails or the user doesn't have javascript support. Use this template:

<form action="servercode.aspx" onsubmit="return ajax submit()">
...
.
.
.

function ajax_submit()
{
// if ajax submission successfull
return false;

//else if ajax submssion failed
return true;
}

So if the ajax postback to the server was successful post back to the action URL will not take place. Hence, if you pass false to onsubmit, the form will not postback. However if you return true to onsubmit the form will do a traditional post back.

In conclusion, since we only return false if the ajax action was successful the program degrades gracefully to a traditional post back. That is an ajax safe html form!

No comments: