I'm trying to process a form in PHP, however I don't want the page to refresh when the submit button is pressed. Instead I want to check if the email and password is correct; then either log the user in or display an error message (login_error in the example).
All of the code snippets below are in the same file, my question is how do I call a php function using AJAX to process the form in the same file?
Form:
<!-- Model dialog for login button -->
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" role="form" id="login_form" action="index.php" method="POST">
<div class="modal-header">
<h4>Login</h4>
</div>
<div class="modal-body">
<div class="form-group" id="login_error">
<label for="login-username" class="col-sm-2 control-label"></label>
<div class="col-sm-10" style="color: red;">
Oops! Your username or password is incorrect, please try again!
</div>
</div>
<div class="form-group">
<label for="login-username" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input required type="text" class="form-control" name="login-email" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="login-password" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input required type="password" class="form-control" name="login-password" placeholder="Password">
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal" href = "#register" data-toggle="modal" formnovalidate>Register</button>
<button type="submit" class="btn btn-success" name="login_submit" id="login_submit">Login</button>
</div>
</form>
</div>
</div>
</div>
PHP I want to call:
<?php
if (isset($_POST["login_submit"])) {
$email = $_POST["login-email"];
$password = $_POST["login-password"];
if (login($email, $password)) {
die("<script>location.href = 'LoginSystem/cookiecontrol.php?action=set&email=$email'</script>"); // Set the cookie
} else {
echo "<script>$('#login_error').show();</script>";
}
}
?>
JQuery:
<script>
$("#login_error").hide();
$("#login_submit").click(function (e) {
e.preventDefault();
$.ajax({url: '/PHP%20Files/Computing%20Project%20-%20Website/ICTeacher/LoginSystem/wrongpassword.php',
data: {action: 'index.php'},
type: 'post',
success: function (output) {
alert(output);
}
});
});
</script>