I'm using a comment form with a first name field that is supposed to send to the database with the comments, but for some reason even though I have the column first_name in the database it won't send, any suggestions?
P.S
I am aware of any SQL Injection vulnerabilities but thank you for being concerned! I plan to just focus on this problem before going further.
Thank you for helping!
<?php
session_start();
$loggedIn = false;
if (isset($_SESSION['loggedIn']) && isset($_SESSION['name'])) {
$loggedIn = true;
}
$conn = new mysqli('localhost', '', '', 'profiles2');
function createCommentRow($data) {
global $conn;
$response = '
<div class="comment">
<div class="user">'.$data['name'].' <span class="time">'.$data['createdOn'].'</span></div>
<div class="userComment">'.$data['comment'].'</div>
<div class="reply">REPLY</div>
<div class="replies">';
$sql = $conn->query("SELECT replies.id, name, comment, DATE_FORMAT(replies.createdOn, '%Y-%m-%d') AS createdOn FROM replies INNER JOIN users ON replies.userID = users.id WHERE replies.commentID = '".$data['id']."' ORDER BY replies.id DESC LIMIT 1");
while($dataR = $sql->fetch_assoc())
$response .= createCommentRow($dataR);
$response .= '
</div>
</div>
';
return $response;
}
if (isset($_POST['getAllComments'])) {
$start = $conn->real_escape_string($_POST['start']);
$response = "";
$sql = $conn->query("SELECT comments.id, name, comment, DATE_FORMAT(comments.createdOn, '%Y-%m-%d') AS createdOn FROM comments INNER JOIN users ON comments.userID = users.id ORDER BY comments.id DESC LIMIT $start, 20");
while($data = $sql->fetch_assoc())
$response .= createCommentRow($data);
exit($response);
}
if (isset($_POST['addComment'])) {
$comment = $conn->real_escape_string($_POST['comment']);
$isReply = $conn->real_escape_string($_POST['isReply']);
$commentID = $conn->real_escape_string($_POST['commentID']);
$first_name = $conn->real_escape_string($_POST['first_name']);
if ($isReply != 'false') {
$conn->query("INSERT INTO replies (comment, commentID, userID, createdOn) VALUES ('$comment', '$commentID', '".$_SESSION['userID']."', NOW())");
$sql = $conn->query("SELECT replies.id, name, comment, DATE_FORMAT(replies.createdOn, '%Y-%m-%d') AS createdOn FROM replies INNER JOIN users ON replies.userID = users.id ORDER BY replies.id DESC LIMIT 1");
} else {
$conn->query("INSERT INTO comments (userID, first_name, comment, createdOn) VALUES ('".$_SESSION['userID']."','".$first_name."','$comment',NOW())");
$sql = $conn->query("SELECT comments.id, name, comment, DATE_FORMAT(comments.createdOn, '%Y-%m-%d') AS createdOn FROM comments INNER JOIN users ON comments.userID = users.id ORDER BY comments.id DESC LIMIT 1");
}
$data = $sql->fetch_assoc();
exit(createCommentRow($data));
}
if (isset($_POST['register'])) {
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$sql = $conn->query("SELECT id FROM users WHERE email='$email'");
if ($sql->num_rows > 0)
exit('failedUserExists');
else {
$ePassword = password_hash($password, PASSWORD_BCRYPT);
$conn->query("INSERT INTO users (name,email,password,createdOn) VALUES ('$name', '$email', '$ePassword', NOW())");
$sql = $conn->query("SELECT id FROM users ORDER BY id DESC LIMIT 1");
$data = $sql->fetch_assoc();
$_SESSION['loggedIn'] = 1;
$_SESSION['name'] = $name;
$_SESSION['email'] = $email;
$_SESSION['userID'] = $data['id'];
exit('success');
}
} else
exit('failedEmail');
}
if (isset($_POST['logIn'])) {
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$sql = $conn->query("SELECT id, password, name FROM users WHERE email='$email'");
if ($sql->num_rows == 0)
exit('failed');
else {
$data = $sql->fetch_assoc();
$passwordHash = $data['password'];
if (password_verify($password, $passwordHash)) {
$_SESSION['loggedIn'] = 1;
$_SESSION['name'] = $data['name'];
$_SESSION['email'] = $email;
$_SESSION['userID'] = $data['id'];
exit('success');
} else
exit('failed');
}
} else
exit('failed');
}
$sqlNumComments = $conn->query("SELECT id FROM comments");
$numComments = $sqlNumComments->num_rows;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>YouTube Comment System</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style type="text/css">
.comment {
margin-bottom: 20px;
}
.user {
font-weight: bold;
color: black;
}
.time, .reply {
color: gray;
}
.userComment {
color: #000;
}
.replies .comment {
margin-top: 20px;
}
.replies {
margin-left: 20px;
}
#registerModal input, #logInModal input {
margin-top: 10px;
}
</style>
</head>
<body>
<div class="modal" id="registerModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Registration Form</h5>
</div>
<div class="modal-body">
<input type="text" id="userName" class="form-control" placeholder="Your Name">
<input type="email" id="userEmail" class="form-control" placeholder="Your Email">
<input type="password" id="userPassword" class="form-control" placeholder="Password">
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="registerBtn">Register</button>
<button class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal" id="logInModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Log In Form</h5>
</div>
<div class="modal-body">
<input type="email" id="userLEmail" class="form-control" placeholder="Your Email">
<input type="password" id="userLPassword" class="form-control" placeholder="Password">
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="loginBtn">Log In</button>
<button class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="container" style="margin-top:50px;">
<div class="row">
<div class="col-md-12" align="right">
<?php
if (!$loggedIn)
echo '
<button class="btn btn-primary" data-toggle="modal" data-target="#registerModal">Register</button>
<button class="btn btn-success" data-toggle="modal" data-target="#logInModal">Log In</button>
';
else
echo '
Log Out
';
?>
</div>
</div>
<div class="row" style="margin-top: 20px;margin-bottom: 20px;">
<div class="col-md-12" align="center">
<iframe width="560" height="315" src="https://www.youtube.com/embed/u2O_QyPfdpE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</div>
<div class="form">
<form action="search_page.php" method="post">
<input type="text" name="search" />
<button>Search</button>
</form>
</div>
<div class="row">
<div class="col-md-12">
<form method="POST" action="index.php">
<input type="text" name="first_name" placeholder="First Name...">
<textarea class="form-control" id="mainComment" placeholder="Add Public Comment" cols="30" rows="2"></textarea><br>
<input type="submit" value="Comment" style="float:right" class="btn-primary btn" onclick="isReply = false;" id="addComment">
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h2><b id="numComments"><?php echo $numComments ?> Comments</b></h2>
<div class="userComments">
</div>
</div>
</div>
</div>
<div class="row replyRow" style="display:none">
<div class="col-md-12">
<textarea class="form-control" id="replyComment" placeholder="Add Public Comment" cols="30" rows="2"></textarea><br>
<button style="float:right" class="btn-primary btn" onclick="isReply = true;" id="addReply">Add Reply</button>
<button style="float:right" class="btn-default btn" onclick="$('.replyRow').hide();">Close</button>
</div>
</div>
<script src="http://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script type="text/javascript">
var isReply = false, commentID = 0, max = <?php echo $numComments ?>;
$(document).ready(function () {
$("#addComment, #addReply").on('click', function () {
var comment;
if (!isReply)
comment = $("#mainComment").val();
else
comment = $("#replyComment").val();
if (comment.length > 5) {
$.ajax({
url: 'index.php',
method: 'POST',
dataType: 'text',
data: {
addComment: 1,
comment: comment,
isReply: isReply,
commentID: commentID
}, success: function (response) {
max++;
$("#numComments").text(max + " Comments");
if (!isReply) {
$(".userComments").prepend(response);
$("#mainComment").val("");
} else {
commentID = 0;
$("#replyComment").val("");
$(".replyRow").hide();
$('.replyRow').parent().next().append(response);
}
}
});
} else
alert('Please Check Your Inputs');
});
$("#registerBtn").on('click', function () {
var name = $("#userName").val();
var email = $("#userEmail").val();
var password = $("#userPassword").val();
if (name != "" && email != "" && password != "") {
$.ajax({
url: 'index.php',
method: 'POST',
dataType: 'text',
data: {
register: 1,
name: name,
email: email,
password: password
}, success: function (response) {
if (response === 'failedEmail')
alert('Please insert valid email address!');
else if (response === 'failedUserExists')
alert('User with this email already exists!');
else
window.location = window.location;
}
});
} else
alert('Please Check Your Inputs');
});
$("#loginBtn").on('click', function () {
var email = $("#userLEmail").val();
var password = $("#userLPassword").val();
if (email != "" && password != "") {
$.ajax({
url: 'index.php',
method: 'POST',
dataType: 'text',
data: {
logIn: 1,
email: email,
password: password
}, success: function (response) {
if (response === 'failed')
alert('Please check your login details!');
else
window.location = window.location;
}
});
} else
alert('Please Check Your Inputs');
});
getAllComments(0, max);
});
function reply(caller) {
commentID = $(caller).attr('data-commentID');
$(".replyRow").insertAfter($(caller));
$('.replyRow').show();
}
function getAllComments(start, max) {
if (start > max) {
return;
}
$.ajax({
url: 'index.php',
method: 'POST',
dataType: 'text',
data: {
getAllComments: 1,
start: start
}, success: function (response) {
$(".userComments").append(response);
getAllComments((start+20), max);
}
});
}
</script>
</body>
</html>
It appears to me that you are making an Ajax call with addComment set to 1, but you are not sending the first_name, you are only sending comment, commentID and isReply.
Your form needs an ID on the first_name
<form method="POST" action="index.php">
<input type="text" name="first_name" id='first_name' placeholder="First Name...">
Then, send the first name value in your addComment ajax call like this:
First, get the value of first_name
var first_name = $("first_name").val()
...
Then add it to ajax call:
data: {
first_name:first_name,
addComment: 1,
comment: comment,
isReply: isReply,
commentID: commentID
I have some trouble with my login form using ajax and php, could somebody con solve this??
This is code html:
login.html
<div id="id01" class="modal">
<form class="modal-content animate" action="" method="POST" id="login-form">
<div class="container">
<label for="login-email"><b>Username</b></label>
<input type="text" placeholder="Enter Email" id="login-email" name="login-email" required>
<label for="login-password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="login-password" name="login-password" required>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label><br>
<span id="showError"></span>
<button type="submit" id="btn-login" name="btn-login">Login</button>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancel-btn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
<script>
$(document).ready(function(){
$("#btn-submit").click(function{
var login-email = $("#login-email").val();
var login-password = $("#login-password").val();
var error = $("#showError");
if(login-email != "" && login-password != ""){
$.ajax({
url: "checkLogin.php",
type: "POST",
data: { login-email: login-email, login-password: login-password},
success: function(response){
var msg = "";
if(response == "success"){
window.location = 'profile.php';
} else {
msg = "Tên đăng nhập hoặc mật khẩu không chính xác.";
}
$('#id01').css({"display": "block"});
error.html(msg);
}
});
} else {
error.html("Email đăng nhập hoặc mật khẩu không được bỏ trống.");
return false;
}
});
});
</script>
and this is code php
login.php
if(isset($_POST["btn-login"])){
$email = trim($_POST["login-email"]);
$password = trim($_POST["login-password"]);
$sql_login = "SELECT email, password, permission FROM users where email='$email' and password='$password'";
$db->query($sql_login);
$rows = $db->findOne();
$permission = $rows['permission'];
if($rows['email'] == $email && $rows['password'] == $password){
echo "success";
} else {
echo "fail";
}
exit();
}
It seem to be not to load into ajax and php code cause i've try so many time but i didn't know the bugs in here.
you call checkLogin.php but the code php is in login.php
In the login.php code, you check the btn-login but the post data from client have no btn-login
{ login-email: login-email, login-password: login-password}
so the if block will never work.
if(isset($_POST["btn-login"])){
...
}
you can change like this
if(isset($_POST["login-email"]) && isset($_POST["login-password"])){
...
}
It appears at first glance that your jQuery is referencing btn-submit but your html defines this as btn-login instead.
I am building an event registration system which displays event registration list if the user is logged in without page refresh using Ajax. However, when I try to login I get undefined index name on line echo "Hello ".$_SESSION["name"]."<br/>"; in index.php. My code is:-
index.php:-
<?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Registration</title>
<link href="style.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="crossorigin="anonymous"></script>
<script src="script.js"></script>
</head>
<body>
<div id="wrapper">
<!--Login div-->
<div id="logincontainer">
<form id="loginform" method="post">
<h3>Login</h3>
<div class="display-error" style="display: none;"></div>
<input type="email" name="lemail" placeholder="Enter email address" required>
<input type="password" name="lpassword" placeholder="Enter password" required>
<input type="submit" value="Sign In">
<p>Forgot Password</p>
<p id="bottom">Don't have an account yet? Sign up</p>
</form>
</div>
<div id="signupcontainer">
<form id="registerform" method="post">
<h3>Register</h3>
<div class="display-error" style="display: none;"></div>
<input type="text" name="rname" placeholder="Full Name" required>
<input type="email" name="remail" placeholder="Enter valid email" required>
<input type="password" name="rpassword" placeholder="Password" required>
<input type="text" name="rmobile" maxlength="10" pattern="[0-9]{10}" placeholder="Mobile" required>
<input type="submit" value="Create Account">
<p id="bottom">Already have an account? Sign In</p>
</form>
</div>
<!--Testing refresh portion-->
<div id="after-login" style="display: none;">
<?php
echo "Hello ".$_SESSION["name"]."<br/>";
echo '<span class="glyphicon glyphicon-logout"></span>Sign Out<br/>';
?>
<form id="events" method="post">
Code Ardor<input type="checkbox" name="coding[]" value="ardor">
Designophy<input type="checkbox" name="coding[]" value="design"><br>
<input type="submit" value="Submit" name="submit-btn">
</form>
</div>
<!--Testing portion ends-->
</div>
<script>
$(document).ready(function(){
$("#loginform").submit(function(){
var data = $("#loginform").serialize();
checkRecords(data);
return false;
});
function checkRecords(data){
$.ajax({
url : 'loginprocess.php',
data : data,
type : 'POST',
dataType : 'json',
success: function(data){
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#logincontainer").hide();
$("#after-login").show();
}
else{
$(".display-error").html("<ul>"+data.msg+"</ul");
$(".display-error").css("display","block");
}
},
error: function(){
alert("Email/Password is Incorrect");
}
});
}
});
</script>
<!--Signup Ajax-->
<script>
$(document).ready(function(){
$("#registerform").submit(function(){
var data = $("#registerform").serialize();
signupRecords(data);
return false;
});
function signupRecords(data){
$.ajax({
url : 'signupprocess.php',
data : data,
type : 'POST',
dataType : 'json',
success: function(data){
if(data.code == 200){
alert('You have successfully Signed Up \n Please Login now.');
setTimeout(function(){
location.reload();
},500);
}
else{
$(".display-error").html("<ul>"+data.msg+"</ul");
$(".display-error").css("display","block");
}
},
error: function(jqXHR,exception){
console.log(jqXHR);
}
});
}
});
</script>
</body>
loginprocess.php
<?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
$errorMsg = "";
$email = trim($_POST["lemail"]);
$password = trim($_POST["lpassword"]);
if(empty($email)){
$errorMsg .= "<li>Email is required</li>";
}
else{
$email = filterEmail($email);
if($email == FALSE){
$errorMsg .= "<li>Invalid Email Format</li>";
}
}
if(empty($password)){
$errorMsg .= "<li>Password Required.</li>";
}
else{
$password = $password;
}
if(empty($errorMsg)){
$query = $db->prepare("SELECT password from users WHERE email = ?");
$query->execute(array($email));
$pwd = $query->fetchColumn();
if(password_verify($password, $pwd)){
$_SESSION['email'] = $email;
//Testing piece
$qry = $db->prepare("SELECT name from users WHERE email = ?");
$qry->execute(array($email));
$nme = $qry->fetchColumn();
$_SESSION['name']=$nme;
//Testing code ends
echo json_encode(['code'=>200, 'email'=>$_SESSION['email']]);
exit;
}
else{
json_encode(['code'=>400, 'msg'=>'Invalid Email/Password']);
exit;
}
}
else{
echo json_encode(['code'=>404, 'msg'=>$errorMsg]);
}
?>
As far as I can see the problem is that after login call you DO NOT reload the #after-login container contents - you only show it.
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#logincontainer").hide();
$("#after-login").show();
}
In the other words the #after-login contents only load on the first page load (before login) and then are not updated by your ajax call (only then you would have access to $_SESSION["name"]).
IMHO proper solution would be to return the $_SESSION["name"] value in the loginprocess.php response and update it in the #after-login container before showing it (eg. use an empty span where the name should appear which you'll fill out on login).
//Something like
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("span#name_placeholder").text(data.name) //return name from loginprocess.php
$("#logincontainer").hide();
$("#after-login").show();
}
The best solution would to be to create a html element like this for the
<div id="after-login" style="display: none;">
<h5 id="Username"></h5>
<?php
echo '<span class="glyphicon glyphicon-logout"></span>Sign Out<br/>';
?>
<form id="events" method="post">
Code Ardor<input type="checkbox" name="coding[]" value="ardor">
Designophy<input type="checkbox" name="coding[]" value="design"><br>
<input type="submit" value="Submit" name="submit-btn">
</form>
</div>
then after this include the username in the json like this
$qry = $db->prepare("SELECT name from users WHERE email = ?");
$qry->execute(array($email));
$nme = $qry->fetchColumn();
//$_SESSION['name']=$nme;
//Testing code ends
echo json_encode(['code'=>200, 'email'=>$_SESSION['email'],'username'=>$nme]);
exit;
on the ajax call you can now access the json response with the username included and feed the span element with the username like this
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#username").test(data.username);
$("#logincontainer").hide();
$("#after-login").show();
}
I'm trying to redirect a user after he presses a sign-in button. So it happens, and the if condition is not met, and the data itself is correct with no extra characters and contains a single one "A". for some reason it won't work.
I have tried to use the trim() function but to no avail.
Here is my code:
$("#login").click(function(event){
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url: "login.php",
method: "POST",
data: {userLogin: 1, userEmail:email, userPassword:pass},
success: function(data){
if(data!= "A"){
alert(data);
}else{
window.location.href="profile.php";
}
}
})
})
And this is the PHP:
<?php
include 'connection/connect.php';
session_start();
if(isset($_POST["userLogin"])){
$email = mysqli_real_escape_string($con, $_POST["userEmail"]);
$password = md5($_POST["userPassword"]);
$sql = "SELECT * FROM user_info WHERE email = '$email' AND password = '$password'";
$run_query = mysqli_query($con, $sql);
$count = mysqli_num_rows($run_query);
if($run_query===false){
echo mysqli_error($con);
}
elseif ($count == 1){
$row = mysqli_fetch_array($run_query);
$_SESSION["uid"] = $row["user_id"];
$_SESSION["name"] = $row["first_name"];
echo trim("A");
}
}
?>
And the HTML:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<li>SignIn
<ul class="dropdown-menu">
<div style="width: 300px;">
<div class="panel panel-primary">
<div class="panel-heading">Login</div>
<div class="panel-heading">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" required />
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" required />
<p><br/></p>
Forgotten Password<input type="submit" class="btn btn-success" id="login" value="Login">
</div>
<div class="panel-footer" id="e_msg"></div>
</div>
</div>
</ul>
</li>
</body>
</html>
furthermore, when i go directly to the page "profile.php", the user is logged in. That means that the data is passed correctly.
What can be the problem? Thanks.
Edit, the alert prints "A".
try javascript trim() method to compare string.
if(data.trim()=="A"){
window.location.href="profile.php";
}else{
alert(data);
}
I'm new to Jquery, and I'm trying to create a login page, using JQuery and PHP but it doesn't respond when I click the login button, what I want is that after the login is success it redirect to index.html.
here is the JQuery code :
<script type="text/javascript" >
$(document).ready(function() {
$("form#memberlogin").submit(function(e) {
dataString = $(this).serialize();
$.post("check_login.php", dataString, function(data) {
$('form#memberlogin').hide();
window.location="index.html"
});
e.preventDefault();
});
});
</script>
Here is my form code :
<form id="memberlogin" class="form-horizontal" method="post">
<fieldset>
<div class="input-prepend" title="Username" data-rel="tooltip">
<span class="add-on"><i class="icon-user"></i></span><input id="username" autofocus class="input-large span10" name="username" id="username" type="text" value="admin" />
</div>
<div class="clearfix"></div>
<div class="input-prepend" title="Password" data-rel="tooltip">
<span class="add-on"><i class="icon-lock"></i></span><input id="password" class="input-large span10" name="password" id="password" type="password" value="admin123456" />
</div>
<div class="clearfix"></div>
<div class="input-prepend">
<label class="remember" for="remember"><input type="checkbox" id="remember" />Remember me</label>
</div>
<div class="clearfix"></div>
<p class="center span5">
<button type="submit" class="btn btn-primary">Login</button>
</p>
</fieldset>
</form>
And this is my php code :
<?php
ob_start();
$con=mysql_connect(localhost,"root","-----");
if(!con)
{
die(mysql_error());
exit();
}
mysql_select_db("sure") or die(mysql_error());
$user=$_POST['username'];
$pass=$_POST['password'];
if(get_magic_quotes_gpc()){
$user = stripslashes($user); //mencegah mysql injection
$pass = stripslashes($pass);
}
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$result=mysql_query("SELECT * FROM user WHERE username='$user' and password='$pass'") or die(mysql_error());
$count=mysql_num_rows($result);
if($count==1)
{
session_register("user");
session_register("pass");
$_SESSION['username']=$_POST['user'];
$_SESSION['id']=mysql_result($result,0,'id');
echo 'correct';
header("location:index.html");
}
else
{
die("id atau password anda salah");
exit();
}
mysql_close($con);
ob_end_flush();
?>
try with this code.
if($count==1)
{
session_register("user");
session_register("pass");
$_SESSION['username']=$_POST['user'];
$_SESSION['id']=mysql_result($result,0,'id');
echo 'Y';
//header("location:index.html");
}
else
{
die("id atau password anda salah");
exit();
}
in javascript:
$.post("check_login.php", dataString, function(data) {
// data is the response sent from the check_login.php
// display the type of data
console.log( typeof data );
console.log( data );
// if data is Y
var reg = /Y/g;
// regex to check the result
if( reg.test(data) ){
console.log('IN');
$('form#memberlogin').hide();
//top.location.href = "index.html";
} else {
console.log('OUT');
// PHP dies message here.
//alert(data);
}
return false;
});
try to check the response in firebug console tab.
Try to use href like,
window.location.href="index.html"
Read this What's the difference between window.location= and window.location.replace()?