I have 3 files: 1. Simple form with email and password 2. login_validate.php to validate form input against database 3. login.js to perform ajax task
I tried to validate form with just login_validate.php and everything worked for me. But when i tried to use ajax(login.js), it always tells me wrong email and password even I tried to type in correct email and password in form. Below is my code, please advice what is wrong with it?
Here is my form:
<div id="login_result"></div>
<form action="login_validate.php" method="post">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
<input type="password" class="form-control" id="pass" name="pass" placeholder="Password">
<button type="submit" class="btn btn-default" name="submit" id="submit">Submit</button>
</form>
Here is my login_validate.php:
<?php
require("configs/dbconnect.php");
if(isset($_POST["dangnhap"])){
$email=mysql_real_escape_string($_POST["email"]);
$pass=mysql_real_escape_string($_POST["pass"]);
$sql = 'SELECT name, email, pass, visible FROM user WHERE email = "'.$email.'" AND pass = "'.$pass.'"';
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
$num_rows= mysql_num_rows($result); // Get the number of rows
if($num_rows > 0){
$row = mysql_fetch_array($result);
echo 1;
$_SESSION["email"]=$row["email"];
$_SESSION["pass"]=$row["pass"];
$_SESSION["name"]=$row["name"];
}
else{
echo 0;
}
}
?>
Here is my login.js:
$(document).ready(function(){
$('#email').focus(); // Focus to the username field on body loads
$('#submit').click(function(){ // Create `click` event function for login
var email = $('#email'); // Get the username field
var pass = $('#pass'); // Get the password field
var login_result = $('#login_result'); // Get the login result div
login_result.html('loading..'); // Set the pre-loader can be an animation
if(email.val() == ''){ // Check the username values is empty or not
email.focus(); // focus to the filed
login_result.html('<span class="error">Enter the username</span>');
return false;
}
if(pass.val() == ''){ // Check the password values is empty or not
pass.focus();
login_result.html('<span class="error">Enter the password</span>');
return false;
}
if(email.val() != '' && pass.val() != ''){ // Check the username and password values is not empty and make the ajax request
var UrlToPass = 'email='+email.val()+'&pass='+pass.val();
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type : 'POST',
cache: false,
data : UrlToPass,
url : 'login_validate.php',
success: function(responseText){ // Get the result and asign to each cases
if(responseText == 0){
login_result.html('<span class="error">Username or Password Incorrect!</span>');
}
else if(responseText == 1){
window.location = 'member/';
}
else{
alert('Problem with sql query');
}
}
});
}
return false;
});
});