开发者

jquery e.preventdefault not working inside $.post

Hi i'm try to check if a title in a form already exists in a database.

My Code does a $.post and gets back the data but it doesn't stop with the e.preventDefault(); or on return false. e.preventDefault(); works when title is empty.

    $(document).ready(function() {
        $('input[id$=btnSubmit]').click(function(e) {
                var title = $("#title").val();
                if (!title) {
                    alert('Please Add a title');
                    return false ;
                    e.preventDefault();
                } else {
                     $.post("http://xendeskt开发者_开发知识库op.nl/uploader/checktitle.php",{ title:$(this).val() } ,function(data) {
                        if(data=='exists') {
                            alert('This title already exists');
                            e.preventDefault();
                        }
                     });
                }
                var description = $("#description").val();
                if (!description) {
                    alert('Please Add a description');
                    return false ;
                    e.preventDefault();
                }


The $.post request happens asynchronously, so the button's default action hasn't been prevented until the the server sends back its response (which will just not happen on time) - or rather, execution flows past that point and the rest of the handler gets executed, causing the form to submit.


return false; is equivalent to BOTH preventing bubbling up and preventing the default.

Neither should go in an AJAX callback - that function gets called outside of the click callback.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜