I want the following ajax request to process form data from form with "#next" id:
$(function () {
$("#next").on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'check_user.php',
dataType: 'json',
data: $('form').serialize(),
success: function (response) {
if(response['found'] === 'true') {
location.href = 'index.php';
} else {
alert('Incorrect username or password');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
And here's the file that contains the form:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/auth_style.css">
<title>Authentication</title>
<script src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script src="js/authentication_ajax.js"></script>
<noscript>JS is disabled. Enable js to continue</noscript>
</head>
<body>
<h1 id="header">Enter your data here</h1>
<form id="#next">
<label for="login">Login</label>
<input type="text" id="login" name="login" placeholder="Enter your login here" required><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Enter your password here" required><br>
<input type="submit" value="Log in">
</form>
<form id="#log_out" action="log_out.php" method="post">
<button type="submit">Log out</button>
</form>
</body>
What's interesting is that when I used just $('form').on('submit', function (e) {
it worked just fine.
You have two error the first one is how to use ids, in the id don't use #
instead use just the name, and into the selector you can use $('#name')
. The second problem is about selector of serialize()
, in this case you can use directly e.target
like:
$(function() { $("#next").on('submit', function(e) { e.preventDefault(); console.log($(e.target).serialize()); /* $.ajax({ type: 'post', url: 'check_user.php', dataType: 'json', data: $(e.target).serialize(), success: function (response) { if(response['found'] === 'true') { location.href = 'index.php'; } else { alert('Incorrect username or password'); } }, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); } }); */ }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1 id="header">Enter your data here</h1> <form id="next"> <label for="login">Login</label> <input type="text" id="login" name="login" placeholder="Enter your login here" required><br> <label for="password">Password</label> <input type="password" id="password" name="password" placeholder="Enter your password here" required><br> <input type="submit" value="Log in"> </form> <form id="log_out" action="log_out.php" method="post"> <button type="submit">Log out</button> </form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.