Adrianno Barello Adrianno Barello - 4 months ago 15
Javascript Question

Why this simple jquery form doesn't work?

Code:

<body id="body-login">
<div id="login">
<form action="http://localhost/projekt2/admin-login" class="admin-login" method="post" accept-charset="utf-8">
<input type="text" name="login" value="" placeholder="Login" minlength="3" maxlength="30" required="required" />
<input type="password" name="haslo" value="" placeholder="Hasło" minlength="3" maxlength="300" required="required" />
<input type="submit" name="submit" value="Zaloguj" />
</form> </div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function()
{
$('form.admin-login').on('submit', function(form) {
form.preventDefault();
$.post('admin-login', $('form.admin-login').serialize(), function(data)
{

});
});
}
</script>
</body>


Above form have preventDefault. So it shouldn't do POST Redirect.

It's made for ajax.
And should not do original POST redirect of from to admin-login.

There is form.preventDefault();

But it doesn't work. And I have redirect.
Like this jquery function wouldn't exist.

What is wrong here?

Answer Source

You just missed one bracket to complete document.ready function.

Here is the corrected code. It worked. I tried it with my localhost.

<body id="body-login">
    <div id="login">
            <form action="http://localhost/projekt2/admin-login" class="admin-login" method="post" accept-charset="utf-8">
<input type="text" name="login" value="" placeholder="Login" minlength="3" maxlength="30" required="required"  />
<input type="password" name="haslo" value="" placeholder="Hasło" minlength="3" maxlength="300" required="required"  />
<input type="submit" name="submit" value="Zaloguj"  />
</form> </div>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
    $(document).ready(function()
    {
        $('form.admin-login').on('submit', function(form) {
            form.preventDefault();
            $.post('admin-login', $('form.admin-login').serialize(), function(data)
            {

            });
        });
    });
    </script>
</body>