form inputs are empty after alert closing

203 views Asked by At
<form id='formregister' autocomplete='off'>
    <input type='text' name='user' maxlength='50' placeholder='* Username'>
    <input type='text' name='pass' maxlength='50' placeholder='* Password'>
    <input type='text' name='name' maxlength='50' placeholder='Ime'>
    <button id='btnregister'>Register</button>
</form>

javascript

$('#btnregister').click(function(){
$.ajax({
    url: 'regpro.php',
    type: 'post',
    data: $('#formregister').serialize(),
    success: function(data) {
        if (data == 'exists') {
            alert ('user already exists');  // after closing form is empty!
        }
        else if (data =='empty'){
            alert ('something is missing'); // after closing form is empty!
        }
        else{
            if (window.confirm('Registration is successfull. Do you wont to login?')){
                window.location.href = 'login.php';  // doesn't work
            }
            else {
                window.location.href = 'index.php';  // doesn't work
            }
        }
    }
});
});

So why form inputs become empty after closing alert, and why redirections don't work after confirm dialog is closed ?

1

There are 1 answers

0
Tri On BEST ANSWER

You should add event.preventDefault(); to your code:

$('#btnregister').click(function(event){
    event.preventDefault();
    ...
});

This method will disable the default submit action of the form when you click on the button.