So, I have a js code calling a backend php script using ajax. The sole purpose of ajax is to send data(username and password) to the said php script. The php script will then query this data on the SQL server, and redirect to dashboard.html on success, or send a error message to the intial ajax request.
However, this is not what happens, and I cant find the source of error. So I tried some console logging and discovered that my SQL is correct and the ajax success function does get "Login Successful" echo if I remove the header() line. But with header() line present in php script, there is no data answer to ajax nor there a redirect to dashboard.html. Is there some concept which I'm missing?
var uname;
var pass;
$(document).ready(function() {
$("#search_button").on("click", function() {
uname = $("#username").val();
pass = $("#password").val();
if (uname == '' | pass == '') {
$("#error_div").empty();
$("#error_div").append('<p> Field cant be blank </p>');
return;
}
$.ajax({
url: 'back-end/login-script.php',
data: ({
'uname': uname,
'pass': pass
}),
method: 'POST',
success: function(data) {
console.log(data);
$("#error_div").empty();
$("#error_div").append('<p>' + data + '</p>');
}
});
});
});
<?php
$host = "localhost";
$db_name = "pwd_lkr_db";
$tbl_name = "user";
$username = $password = $_SESSION["errMsg"] = "";
session_start();
$username = $_POST["uname"];
$password = $_POST["pass"];
if(!empty($username) && !empty($password)) {
//header("location: welcome.php");
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db($db_name, $connection);
$query = mysql_query("SELECT * FROM user WHERE password='$password' AND username='$username'", $connection);
$rows = mysql_num_rows($query);
if($rows == 1) {
$_SESSION["sid"] = $username;
echo "Login Successful";
header("Location: dashboard.html");
exit();
} else {
$_SESSION['errMsg'] = "Username or Password is not valid";
echo $_SESSION['errMsg'];
session_destroy();
}
} else {
die("Username and Password are required!");
}
?>