I have been using this excellent jQuery Form Plugin lately and I came across a little gotcha today. First of all, this jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process. Both of these methods support numerous options which allows you to have full control over how the data is submitted.

So, I had this code to submit my form :-

var options = {
success: showResponse  // post-submit callback
};

$('.btnLogin').click(function(){
$('.frmLogin').ajaxSubmit(options);
return false; // prevent default behaviour
});

// post-submit callback
function showResponse(responseText, statusText)  {
if(jQuery.trim(responseText) == "Success"){
window.location.href = 'home/index.html';
} else {
$('.loginStatus').html(responseText);
}
}

This code is for a simple login form. As is obvious, this code attaches the click event to a Button and then submits the form whenever the button is clicked. The submit is done using the Form Plugin and the response is handled by the ‘showResponse’ function, which checks the response from the server. If successful, it reloads the browser, otherwise it updates the DOM with the error message from the server. Nothing fancy there!

Now, the weird behaviour was that if you use the ‘Return’ Key to submit your form, instead of pressing the button, it would not use the AJAX form, but simply go to the action page as if it were a normal form. And to make things worse, it was in-consistent across all browsers. It was only happening in Safari and Chrome and not happening in IE and Firefox. I did not test any other browsers.

I did not know what the issue was, to be honest, but I thought, surely, capturing and binding the enter key would solve the problem here. So, I came up with this little code:-

//capture the return key
$(".txtLoginForm").bind("keydown", function(e) {
if (e.keyCode == 13) {
$('.frmLogin').ajaxSubmit(options);
return false; //prevent default behaviour
}
});

So, I assigned my two text fields (username and password) a class of ‘txtLoginForm’ and captured the enter/return key and then submitted the form using AJAX. That works for me!

I thought this might be useful for someone!