jQuery Submit Refreshing Page

江枫思渺然 提交于 2019-12-04 06:32:42

my bet it's because of the $(this), try it this way....

$('#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 the error

It could be your JavaScript is failing, so the default behaviour is being executed.

Try to examine the XHR in a tool like Firebug.

Also, you could try event.preventDefault() (where the first argument to your event callback is event).

Use event.preventDefault() to prevent the default action of the event. One benefit is that you can place this before the Ajax request, so that if it fails, you will still have prevented form submission.

Your code is failing because the value of this in your success callback is the global window object. Your attempt to hide it fails. You probably want this to refer to the form, like this:

$('#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 example.

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

should be like:

$(document).ready(function() {
    $('#bin form').submit(function() {
            $.post($(this).attr('action'), {
                success: function(data) { $(this).hide().siblings('form').show(); },
                data: $(this).serialize()
            });
            return false;
        });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!