23

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;
});
​
gdoron
  • 147,333
  • 58
  • 291
  • 367
Dmitri
  • 579
  • 1
  • 9
  • 19

5 Answers5

39

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

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • 1
    +1 for answering the actual question, even as an afterthought – hair raisin May 23 '12 at 23:27
  • +1 Yeah, I was about to write about `stopPropagation` but saw you've already mentioned it :) – VisioN May 23 '12 at 23:28
  • Does that mean if you have `e.preventDefault();` you don't need `return false;` if they both do the same thing? – Nope May 23 '12 at 23:30
  • 1
    See also http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false. – Jonathan S. May 23 '12 at 23:30
  • 2
    @FrançoisWahl. The other way around... `return false` does `e.preventDefault(); + e.stopPropagation()`. so if you want them both, just `return false`. – gdoron May 23 '12 at 23:31
  • @Eric, Thank you for fixing my grammar! I really appreciate it. I added explanations, is it still o.k.? :) – gdoron May 23 '12 at 23:45
4

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.

Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
3

In this instance, return false; prevents the default action (which is the form submitting).

Although it's probably better to use e.preventDefault();

ahren
  • 16,803
  • 5
  • 50
  • 70
2

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.

pbaris
  • 4,525
  • 5
  • 37
  • 61
0

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

The man
  • 129
  • 16