I have made a login form which utilises php, ajax and mysql, the php code seems to work fine as it says that when the user credentials are entered a success message is echoed on the screen.
However the ajax is supposed to take this and process it and open up the index.php page which it fails to do so. However the ajax does work to an extent as my "checking..." message appears as expected. Any help would be greatly appreciated. Please find the code below.
loginajax.js
function chk_ajax_login_with_php() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var params = "username=" + username + "&password=" + password;
var url = "login.php";
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
data: params,
beforeSend: function () {
document.getElementById("status").innerHTML = 'checking...';
},
complete: function () {
},
success: function (html) {
if (html == "success") {
window.location = 'index.php';
}
}
});
}
login.php
<?php
require "header.php";
try
{
$connection = mysql_connect("localhost","root", "dbpassword");
if(!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db("dbname",$connection);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
}catch (Exception $e){
error_log(" DB Error: ".$e->getMessage());
}
if($_POST){
$username=$_POST['username'];
$password=$_POST['password'];
$sql = mysql_query("SELECT * FROM usertable WHERE userID ='".$username."' AND userPass ='".md5($password)."'") or die(mysql_error());
$res=mysql_num_rows($sql);
if($res>0){
$rs_login=mysql_fetch_assoc($sql);
$uid=$rs_login['user_id'];
$_SESSION['sess_uid']=$uid;
echo "success";
}
else{
echo "invalid username or password";
}
}
?>