Search code examples
javascriptjqueryajaxpreventdefault

jQuery submit preventDefault not working when AJAX is includet


Let's say my code would be:

$("form").submit(function (e) {
    e.preventDefault();
    var logemail = $('input[name="logemail"]').val();
    var logpasswort = $('#logpasswort').val();

    if(logpasswort.length < 6)
    {
        alert('wrong pass');
        return false;
    }
});

everything works fine, but my code is:

$("form").submit(function (e) {
    e.preventDefault();
    var logemail = $('input[name="logemail"]').val();
    var logpasswort = $('#logpasswort').val();

    if(logpasswort.length < 6)
    {
        alert('wrong pass');
        return false;
    }

    $.ajax({
        type: 'post',
        url: 'connect.php',
        dataType, 'json',
        data: {mach: "login", email: logemail, passwort: logpasswort},
        success: function(data) {
            if(data["status"] == 'wrongpass'){
            {
                alert('wrong pass');
            }

            if(data["status"] == 'ok')
            {
                alert('good');
            }
        }
    });
});

And the form is just getting submitted because AJAX is included, even when if(logpasswort.length < 6) is true! what's wrong with that??


Solution

  • Your javascript is not getting parsed. Remove the extra "{" at the end of line:

    if(data["status"] == 'wrongpass'){
    

    Side note: stick with the consistent style of putting "{" either at the of the line or on the new line throughout your code.