JQuery Send refresh page

The following code is designed to execute a purely ajax POST request, instead, it seems to execute POST through ajax, and then the browser goes to the answer.

HTML ...

<div id="bin"> <form class="add" method="post" action="/bin/add/"> <p>I'm interested! Save for later.</p> <input type="hidden" name="product_id" value="23423"> <input type="submit" value="Save"> </form> <form style="display:none;" class="remove" method="post" action="/bin/remove/"> <p>I changed my mind--I'm not interested.</p> <input type="hidden" name="product_id" value="23423"> <input type="submit" value="Unsave"> </form> </div> 

jQuery ...

 $('#bin form').submit(function() { $.post($(this).attr('action'),{ success: function(data) { $(this).hide().siblings('form').show() }, data: $(this).serialize() }); return false; }) 

As far as I understand, the string return false; should mean that no matter what calls the submit function or presses the submit button or presses the enter key, it means that my function will be executed and the browser will not move to /bin/add or /bin/remove . But for some reason, the browser changes pages.

Any idea what I'm doing wrong here? Thanks.

+6
javascript jquery html ajax
source share
4 answers

my bid is because of $(this) , try it like this ....

 $('#bin form').submit(function() { var $this = $(this); $.post($this.attr('action'), { success: function(data) { $this.hide().siblings('form').show() }, data: $this.serialize() }); return false; }); 

demo no error

demo with error

+3
source share

Your JavaScript may not work, so the default behavior is performed.

Try learning XHR in a tool like Firebug.

Alternatively, you can try event.preventDefault() (where the first argument to call back your event is event ).

+4
source share

Use event.preventDefault() to prevent the default action for the event. One of the advantages is that you can post this before an Ajax request, so if it fails, you still cannot submit the form.

Your code does not work because this value in your success callback is a global window object. Your attempt to hide it failed. You probably want this refer to the form, for example:

 $('#bin form').submit(function(ev) { var _this = this; ev.preventDefault(); $.post($(this).attr('action'), { success: function() { $(_this).hide().siblings('form').show(); }, data: $(this).serialize() }); }) 

See a working working example .

+1
source share

Is $(...).submit(...) inside a $(document).ready(function(){ code here }); ?

should look like this:

 $(document).ready(function() { $('#bin form').submit(function() { $.post($(this).attr('action'), { success: function(data) { $(this).hide().siblings('form').show(); }, data: $(this).serialize() }); return false; }); }); 
0
source share

All Articles