I'm making a simple login test and the code returns the json response when the fields are empty,but not when the login fails or succeds, like:
- Empty Fields - OK
- Login Succeded - nope
- Login failed - nope
Request:
var loader = $('#trabalhando');
$(function() {
$('form').submit(function(e) {
loader.fadeIn("slow");
e.preventDefault();
$.ajax({
url: 'login.php',
data: $(this).serialize(),
method: 'post',
dataType: 'JSON',
success: function(data){
loader.fadeOut("slow");
console.log(data);
alert(data.resp);
},
error: function(data) {
alert(':(');
loader.fadeOut("slow");
console.log(data);
}
});
});
});
Response:
<?php
header('Content-Type: application/json');
if (isset($_POST['cpf']) && isset($_POST['pass']) && $_POST['cpf'] != "" && $_POST['pass'] != "") {
$cpf = $_POST['cpf'];
$passw = sha1(strrev(md5($_POST['pass'])));
include 'config.php';
$sql = "SELECT * FROM users WHERE cpf = :cp AND passwd = :pw";
$chec = $db->prepare($sql);
$chec->bindParam('cp', $cpf, PDO::PARAM_STR);
$chec->bindParam('pw', $passw, PDO::PARAM_STR);
$chec->execute();
if ($chec->rowCount() > 0) {
echo json_encode(array('resp' => 'nice'));
} else {
echo json_encode(array('resp' => 'nope'));
}
} else {
echo json_encode(array('resp' => 'fields'));
}
?>
Edit: updated the code