Karthik Sekar
Karthik Sekar

Reputation: 178

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;   
}); 

Upvotes: 0

Views: 139

Answers (4)

Pawan
Pawan

Reputation: 605

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.

Upvotes: 0

RRikesh
RRikesh

Reputation: 14411

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:

Upvotes: 0

Andrew M
Andrew M

Reputation: 4288

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();   
});  

Upvotes: 2

bugwheels94
bugwheels94

Reputation: 31950

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

Upvotes: 2

Related Questions