What does "return false;" do? - javascript

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 false inside a callback prevents the default behaviour. For example, in a submit event, it doesn't submit the form.
return false also stops bubbling, so the parents of the element won't know the event occurred.
return false is equivalent to event.preventDefault() + event.stopPropagation()
And of course, all code that exists after the return xxx line 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 false and event.preventDefault():
Markup:
<div id="theDiv">
<form id="theForm" >
<input type="submit" value="submit"/>
</form>
</div>​
JavaScript:
$('#theDiv').submit(function() {
alert('DIV!');
});
$('#theForm').submit(function(e) {
alert('FORM!');
e.preventDefault();
});​
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:
$('#theDiv').submit(function() {
alert('DIV!');
});
$('#theForm').submit(function(event) {
alert('FORM!');
return false;
// Or:
event.preventDefault();
event.stopPropagation();
});​
The div wouldn't even know there was a form submission.
Live DEMO
What does return false do in vanilla javascript events
return false from a DOM2 handler (addEventListener) does nothing at all (neither prevents the default nor stops bubbling; from a Microsoft DOM2-ish handler (attachEvent), it prevents the default but not bubbling; from a DOM0 handler (onclick="return ..."), it prevents the default (provided you include the return in the attribute) but not bubbling; from a jQuery event handler, it does both, because that's a jQuery thing. Details and live tests here – T.J. Crowder

Any code after return statement in a function will never be executed. It stops executing of function and make this function return value passed (false in this case). Your function is "submit" event callback. If this callback returns false, form will not be submitted actually. Otherwise, it will be submitted as it would do without JavaScript.

In this instance, return false; prevents the default action (which is the form submitting).
Although it's probably better to use e.preventDefault();

because of ajax you do not want your form to be submitted with the normal way. So you have to return false in order to prevent the default behavior of the form.

The return statement ends function execution
This is important. Using return causes your code to short-circuit and stop executing immediately, preventing the next line of code from executing

Related

using ajax to display a different php page

<script>
//jQuery('#frmSearch').click(function() {
jQuery(function(){
jQuery('#frmSearch').on('click', function(e){
e.preventDefault();
jQuery.ajax({
type: 'POST',
url: 'mutualfundsprices/do_price_archive.php',
data: jQuery('#frmSearch').serialize(),
success: function(data) {
jQuery('#DisplayResult').html(data);
}
});
return false;
});
});
</script>
the above is my JavaScript to display a different PHP page but after loading the result, the result disappears.
What is wrong with my code?
I guess #frmSearch is a form on your DOM, right?
My guess is that the form is being submitted twice, once using your onclick function (ajax), and then the second may reload the page so that your AJAX-loaded HTML disappears. But I may be out of line here.
You are assigning an onclick, which is quite uncommon for forms. But still, e.preventDefault and return false; on an onclick event won't prevent the form to submitting if you ever click on the submit button. You might want to use the onsubmit event of the form instead, or, better yet, avoid having a submit button but rather have a normal button if you want to handle form submissions always using AJAX in your callback function.

jquery $.post explain

I wrote the following code to post data with jQuery, It's working fine, but without return false;, the code didn't work, I found this return statement after 1 full day of searching...
Could somebody please tell me, what is the use of return false; after the end of $.post?
I am a newbie in jQuery and would like to get a better understanding of this.
$("#formid").submit( function () {
$.post(
'ajax.php',
$(this).serialize(),
function(data){
$("#result").html(data);
$("#result").fadeIn('slow');
}
);
return false;
});
The return false; here is not used for $.post method of AJAX instead it is used to prevent the form(#formid) submission which can cancel your AJAX request
If you remove the return false;, you will see that the browser continues to submit the form (not using AJAX). Returning false will prevent the browser from doing the default action, resulting in only the AJAX call occurring.
A similar result can be gotten by calling preventDefault() on the event object passed into the submit event.
For example:
$("#formid").submit( function (event) {
$.post(
'ajax.php',
$(this).serialize(),
function(data){
$("#result").html(data);
$("#result").fadeIn('slow');
}
);
event.preventDefault();
});
Return false stops the default form action from being executed whenever a user clicks the submit button. Only the jQuery part is executed. Else, the whole page would have been reloaded upon form submission.
You can read about that on the.submit() page on jQuery API.
There's the following paragraph:
when the form is submitted, the message is alerted. This happens prior
to the actual submission, so we can cancel the submit action by
calling .preventDefault() on the event object or by returning false
from our handler. We can trigger the event manually when another
element is clicked:
The return false is actually preventing the default action that is form submit. If you don't write that statement, your form is getting submitted.

action button after the second click

I have a button in my form. I need my form to be processed after the first click (or pressing Enter) on the button, and after that, if some conditions would be true, I do something like submitting the form by the second click or pressing Enter key on the button.
What do you think I have to do?
Create a (boolean) variable that saves your state, which is set to true when the first click (or action) has happened and your condition is true. Then submit on the second action when the variable is true.
If the condition has to be matched on both clicks (I guess so) consider the following:
$(function() {
var first = false;
$("form").submit(function() {
if(first && checkCondition())
submit();
if(!first && checkCondition())
first = true;
e.preventDefault();
});
});
so in basic code:
var answered = false;
$(function() {
$("form").submit(function() {
if(answered == false) {
answered = true;
return false;
}
});
});
If I've understood what you're trying to do correctly, you could bind an event handler to the submit event. That event handler will handle your validation, but if you use the jQuery one method, it will only be executed once. The next time the submit event is triggered, the form will submit as usual:
$("yourForm").one("submit", function(e) {
e.preventDefault(); //Stop the form from being submitted
//Do stuff
});
The result is effectively the same as #Manuel van Rijn's answer, but using jQuery's one just makes it a bit shorter and cleaner in my opinion. However, this could also add a slight performance benefit, as the event handler is unbound after it's execution and won't be called again.

2 jQuery events on same action seem to cancel each other

**Update: I have pasted working code in order to erase any ambiguity about what is going on. I have also tried to remove the preventDefault on both handlers, does not help*
I have a form where upon the button click, a JS event needs to happen, and the form needs to submit.
As per the code below, what I thought would happen is: alert(button), then alert(form), or vice versa. I do not care about sequence.
If i run it however, the alert(button) will show up, but the alert(form) will not.
If i comment out the code for the button, the form alert comes up.
Do i have some fundamental misunderstanding of how this is supposed to work?
jQuery(document).ready(function(){
$("form.example").submit(function(event){
event.preventDefault();
alert("form submitted");
});
$("form.example button").click(function(event){
event.preventDefault();
alert("button clicked");
});
)};
<form class="example" action="/v4test">
<button type="submit">Meow!</button>
</form>
After edit of OP
You do not need to preventDefault of the click.... only the submit... here is you working code:
jsFiddle example
jQuery(document).ready(function(){
$('form.example').submit(function(event){
event.preventDefault();
alert("form submitted");
// stop submission so we don't leave this page
});
$('form.example button').click(function() {
alert("button clicked");
});
});​
old answer
You can simply put your .click() and .submit() handlers in series, and they should not cancel out. You have some syntax errors in your pseudo code.... maybe those are causing problems?
Another potential problem is that $("form button") targets the HTML <button> tags. If you use <input type="button" /> you should use $("form:button") and note that <input type="submit" /> is not a button. Anyway, I'll assume you are in fact using the <button> tags.
Usually return false is used inside .submit(function() { ... });. This stops the form from being submited through HTML. s**[topPropagation][6]** is very different. It deals with stopping events "bubbling up" to the parents of elements....... But I don't see how this would effect your case.
If you are doing a true HTML submission, make sure to put your .click() handler first, since a true HTML submission will cause you to leave the page.
If you use return false inside .submit(), the form will not be submitted through the HTML, and you'll have to handle the submission with jQuery / Javascript / AJAX.
Anyway, here is a demonstration of both the .click() and .submit() events firing in series... the code is below:
jsFiddle Example
$(function() {
$('form button').click(function() {
// Do click button stuff here.
});
$('form').submit(function(){
// Do for submission stuff here
// ...
// stop submission so we don't leave this page
// Leave this line out, if you do want to leave
// the page and submit the form, but then the results of your
// click event will probably be hard for the user to see.
return false;
});
});​
The above will trigger both handlers with the following HTML:
<button type="submit">Submit</button>
As a note, I suppose you were using pseudo code, but even then, it's much easier to read, and one is sure you're not writing syntax errors, if you use:
$('form').submit(function() { /*submits form*/ });
$('form button').click(function() { /*does some action*/ });
If you put a return false on the click, it should cancel the default behavior. If you want to execute one then the other, call $('form').submit() within the click function. e.g.
$('form').submit { //submits form}
$('form button').click {
// does some action
$('form').submit();
}
There seems to be a bit of confusion about propagation here. Event propagation (which can be disabled by stopPropagation) means that events "bubble up" to parent elements; in this case, the click event would register on the form, because it is a parent of the submit button. But of course the submit handler on the form will not catch the click event.
What you are interested in is the default action, which in the case of clicking a submit button is to submit the form. The default action can be prevented by either calling preventDefault or returning false. You are probably doing the latter.
Note that in Javascript functions which do not end with an explicit return do still return a value, which is the result of the last command in the function. You should end your click handler with return; or return true;. I have no idea where I got that from. Javascript functions actually return undefined when there is no explicit return statement.
Does clicking the button submit the form? If so:
// Disable the submit action
$("form").submit(function(){
return false;
});
$("form button").click(function(){
// Do some action here
$("form").unbind("submit").submit();
});
If you don't unbind the submit event when you click the button, the submit will just do nothing.

Why is my onsubmit function quitting early and not returning false?

<form method="post" action="/Order/CheckOut/" onSubmit="return Validate()">
and then...
function Validate() {
alert($("#email").val());
return false;
}
The messed up part is when I take out the alert it works fine, the submit fails, but when I put the alert in, it allows the submit to go through... what the heck?
I also tried this:
function Validate() {
if(document.getElementByID("email").value == "test"){
alert("It says test.");
}
return false;
}
and got the same behavior, it would never make it to the return statement...
If I step through the JS with firebug and break at the alert or the if (depending on the version above) it stops there, and I click 'step into' and it just submits the form, why isn't it making it to the return false line?
Why not wrap it in a try block?
function Validate() {
try {
alert($("#email").val());
} catch (e) {
alert("Problem: " + e);
}
return false;
}
You could use event.preventDefault() instead.
$("form[name='myForm']").submit(function(e){
e.preventDefault();
alert($("#email").val());
});
You should attempt to keep your javascript, css, and html all seperate. Don't integrate them, or you'll make the project more difficult to manage. Instead of using the onsubmit attribute in HTML, simply append your logic to the $.submit() method of the form from your javascript as I did above.
This example assumes that you've given your form a name of "myForm." I merely used this in the example as you should itendify which form you're handling the submit-event of, and not use a generic $("form") selector.
If you're already using jQuery you're doing the whole thing wrong to begin with. You shouldn't be manually specifying the onSubmit handler from within the <form> element. Do as #Jon suggested and just bind the submit event:
$("form").submit(function() {
alert($("#email").val());
return false;
});
The problem isn't that your function is returning true. The problem is that the JavaScript in the alert is failing and JavaScript quits interpreting the code. At which point, the browser is continuing with the default action which is to submit the form.
This is why Jonathan Sampson suggests using e.preventDefault() before the alert(), this way the browser doesn't continue with its default behaviour when the alert() fails.

Categories