I wrote a webpage where a user can enter a log entry that is stored on a database and then retrieved and printed on the page using ajax. I am still quite new to ajax and was wondering if somebody could please explain to me what does return false; do at the end of my code? and is it even necessary?
If I put the second ajax code after the return false the code does not work! can you please explain to me why?
//handles submitting the form without reloading page
$('#FormSubmit').submit(function(e) {
//stores the input of today's data
var log_entry = $("#LogEntry").val();
// prevent the form from submitting normally
e.preventDefault();
$.ajax({
type: 'POST',
url: 'behind_curtains.php',
data: {
logentry: log_entry
},
success: function() {
alert(log_entry);
//clears textbox after submission
$('#LogEntry').val("");
//presents successs text and then fades it out
$("#entered-log-success").html("Your Entry has been entered.");
$("#entered-log-success").show().fadeOut(3000);
}
});
//prints new log entries on page upon submittion
$.ajax({
type: 'POST',
url: '/wp-content/themes/childOfFanwood/traininglog_behind_curtains.php',
data: {
log_entries_loop: "true"
},
success: function(data) {
alert(data);
$("#log-entry-container").html("");
$("#log-entry-container").html(data);
}
});
return false;
});
What I’ll write here is true for jQuery events,
For vanilla javascript events read @T.J. Crowder comment at the bottom of the answer
return falseinside a callback prevents the default behaviour. For example, in asubmitevent, it doesn’t submit the form.return falsealso stops bubbling, so the parents of the element won’t know the event occurred.return falseis equivalent toevent.preventDefault()+event.stopPropagation()And of course, all code that exists after the
return xxxline won’t be executed. (as with all programming languages I know)Maybe you find this helpful:
Stop event bubbling – increases performance?
A “real” demo to explain the difference between
return falseandevent.preventDefault():Markup:
JavaScript:
Now… when the user submit the form, the first handler is the form submit, which
preventDefault()-> the form won’t be submitted, but the event bubbles to the div, triggering it’s submit handler.Live DEMO
Now, if the form submit’s handler would cancel the bubbling with
return false:The div wouldn’t even know there was a form submission.
Live DEMO
What does
return falsedo in vanilla javascript events