nick
nick

Reputation: 891

How can I stop an ajax form submit from refreshing page on error callback?

I have this ajax request that is used for login, it redirects on successful login to user dash and on fail I want it to display an alert and not refresh. Is there any way to stop the refresh?

$('#doctor_login').on("submit", function (e) {
frmReg = document.getElementById("doctor_login");

if (frmReg.user_name.value == "") {
    alert("<?php echo _USERNAME_EMPTY_ALERT; ?>"); frmReg.user_name.focus(); return false;
}
else if (frmReg.password.value == "") {
    alert("<?php echo _PASSWORD_IS_EMPTY; ?>"); frmReg.password.focus(); return false;
}
else {
    $.ajax({

        dataType: "html",
        type: 'POST',
        url: '../doctor/handlers/handler_ajax_login.php',
        data: $(this).serialize(),
        success: function (response) {
            console.log(response);
        },
        error: function (response) {

            alert('hi');
        }
    });
}

});

Upvotes: 0

Views: 127

Answers (1)

Simon Davies
Simon Davies

Reputation: 3686

add a return false to prevent it.

 $.ajax({

    dataType: "html",
    type: 'POST',
    url: '../doctor/handlers/handler_ajax_login.php',
    data: $(this).serialize(),
    success: function (response) {
        console.log(response);

    },
    error: function (response) {

        alert('hi');
        return false;
    }
});

or use:

$('#doctor_login').on("submit", function (e) {
     e.preventDefault();

Then you can submit it when you want, as this will prevent it form submiting until you want it to

Upvotes: 1

Related Questions