Search code examples
javascriptjquerypreventdefault

Prevent Default is not working


I have checked around here and none of these solution on here fix my issue. I cannot seem to get the preventDefault() to work. Code below:

Jquery:

$("#changepassword").submit(function(event) {
    event.preventDefault(); // stop normal form submission
    $.ajax({
        url: "changePassword.php",
        type: "POST",
        data: $(this).serialize(), // you also need to send the form data
        dataType: "html",
        success: function(html) {
            $("#s-window").append(html);
        }
    });
});

HTML:

    <div id="s-window">
        <form id="changepassword" action="changePassword.php" method="POST">
            <input type="password" name="currentPassword" placeholder="Current Password"/>
            <input type="password" name="newPassword" placeholder="New Password"/>
            <input type="password" name="confirmPassword" placeholder="Confirm Password"/>
            <input class="button" type="submit" value="Change Password" />
        </form>
    </div>

There are no errors on my conosle. The changePassword.php works as it is supposed to. But rather than updating my #s-window it redirects me to the changePassword.php page

How can I recode this to make everything happen on the page?


Solution

  • You need to wait until document is ready:

    $(document).ready(function(){
        $("#changepassword").submit(function(event) {
            event.preventDefault(); // stop normal form submission
            $.ajax({
                url: "changePassword2.php",
                type: "POST",
                data: $(this).serialize(), // you also need to send the form data
                dataType: "html",
                success: function(html) {
                    $("#s-window").append(html);
                }
            });
        });
    });