I have a designer insisting on a single form field submitted by hitting enter and the post made by AJAX and the response presented by Fancybox.
Problem is the the return false is not preventing the submission of the page.
What am I doing wrong there?
<form id="home_stay_informed_form">
<input name="informed_email" id="home_informed_email" value="Enter your email address..." />
</form>
$('#home_stay_informed_form').submit(function() {
var reg = new RegExp(/^\S+@\S+\.\S+$/);
var em = $("#home_informed_email").val();
if (!reg.test(em)) {
alert('Please correct your email address.');
$("#home_informed_email").focus();
return false;
} else {
$.ajax({
type: "POST",
url: 'listSubscribe.php',
data : 'email=' + em,
success: function(msg) {
$("#home_stay_informed_form_msg").fancybox({
'titlePosition' : 'outside',
'transitionIn' : 'none',
'transitionOut' : 'none'
});
$("#home_informed_email").val('Enter your email address...');
return false;
}
});
}
});
The
return falseneeds to do in thesubmithandler directly, like this:Your
successhandler doesn’t run until the server response comes back, so your function is actually returningundefinedfor thatelsestatement…and thatreturn falseinside doesn’t have any effect. Putting it in thesubmithandler directly like is it above will do what you want, preventing the form submit.A bit cleaner would be
event.preventDefault(), by adding the event parameter here:And replacing
return falsewith