xendesktop
xendesktop

Reputation: 11

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://xendesktop.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();
                }

Upvotes: 1

Views: 2003

Answers (2)

karim79
karim79

Reputation: 342635

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.

Upvotes: 1

Dennis
Dennis

Reputation: 32598

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.

Upvotes: 0

Related Questions