Code

Coding, Programming & Algorithms, Tips, Tweaks & Hacks
Search

Sponsored Ads

Form submission using AJAX & HTML

One of the biggest concerns using AJAX based form submissions are JavaScript related issues :
  • What if JavaScript is disabled or not available on the client's browser ?
  • What if XMLHttpRequest / Msxml2.XMLHTTP / Microsoft.XMLHTTP aren't available ?
  • What if the creation of XMLHttpRequest object failed for some reason ?
  • What if all the JavaScript scripts didn't load properly and screwed up the damn thing ?
  • What if the user clicked the button much faster than the scripts to completely load ? You must be on a real slow connection for this to happen.
The only solution is to give your users the option to automatically fall back to the normal form submission if AJAX doesn't work. Relying solely on client side scripting should only be done only if the application demands it.
HTML
<form id="Comment-Form" action="http://mydomain.com/PostComment" method="post">
<div id="Comment-Box">
<table>
<tr><th>Leave a Comment</th></tr>
<tr><td id="Comment-Box-Msg" style="display:none"></td></tr>
<tr><td><textarea name="Comment" id="Comment-Reply" rows="10" cols="50"></textarea></td></tr>
<tr><td style="text-align:center">
<input type="submit" value="Post Comment" name="Submit" id="Comment-Button"/>
</td></tr>
</table>
</div>
</form>
HTML 4.01
JavaScript
window.onload = function() { init(); }
function init()
 {
        /* 
        This is set only after the entire page is loaded,
        so if the button is clicked way before its loaded,
        it'll 'normal' submit to the form's action value
        */
        document.getElementById("Comment-Button").onclick = PostCommment;
 }
function PostCommment()
 {
        // AJAX error : switch to <form> submit
        if (ajax_error) document.getElementById("Comment-Form").submit();

        // Do the form submission via AJAX

        // To stop the <form> being submitted, since its done via AJAX
        return false;
 }
Javascript 1.5
This way, it ensures that if there is a problem with JavaScript or AJAX in particular, you can always fall back to the normal form submission.
Vanakkam !

1 comments:

sreejith said...

hello kool site