Submit a form using jquery without navigating to another screen
Question
I'm trying to make it so that a form submit doesn't cause the page to navigate and use ajaxSubmit to submit the content. however when I click the submit button, it still navigates to the page in the action attribute of the form. Heres the javascript:
var options = {
success: processLogin
};
$('#loginform').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
and heres the form:
<form id='loginform' action='login.php' method='post'>
<table id='logintable'>
<tr>
<td>Room:</td>
<td><input id='roomname' type='text' name='roomname' /></td>
</tr>
<tr>
<td>Nickname:</td>
<td><input id='nickname' type='text' name='nickname' /></td>
</tr>
<tr>
<td colspan='2' class='center'><input type='submit' value='Submit' /></td>
</table>
</form>
Solution
$('#loginform').submit(function(e) {
e.preventDefault();
$(this).ajaxSubmit(options);
});
OTHER TIPS
Another option is to change the input html tag to <input id="save" type="Button" value="submit" />
which gives you a button that does nothing except provide a javascript hook.
Use the following javascript to ajax submit your form
$("#save").click(function() {
$("#loginform").ajaxSubmit();
}
In doing this you lose the ability to submit the form by pressing enter. You can overcome this with the following piece of jquery:
$("input").keypress(function(e) {
if (e.which == 13) {
$("#save").click();
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow