I have login page. When I enter correct login data ajax working. But when i enter bad login or password script not returning error. How i can fix this, where i take mistake on code? Ajax script
function getdetails()
{
var name = $('#user').val();
var haslo = $('#pass').val();
var request=$.ajax
({
type: "POST",
url: "login.php?id=0",
data: {login:name, pass:haslo}
});
request.fail(function() {
alert("test");
});
request.done(function() {
$('#logowanie').load('index.php #logowanie');
});
};
Form code
function logowanie()
{
if(isset($_SESSION["login"]) && $_SESSION["login"]!==0)
{
echo '<div id="logowanie"> Witaj '.$_SESSION['nick'].' na forum';
echo '<br/><a href="login.php?off=1">Wyloguj</a><br/>';
if($_SESSION['power']>0)
{echo '<a href="panel.php">Panel Admina</a>';}
echo '</div>';
}
else
{
$_SESSION["login"]=0;
$_SESSION['power']=0;
?>
<div id="logowanie">
<font color="red"><B> Login</B></font><input type="text" name="user" size="8" id="user"><br/>
<B><font color="red">Hasło</font></B><input type="password" name="pass" size="8" id="pass"><br/>
<input type="submit" value="Zaloguj" name="przycisk" onClick ="getdetails()">Jeżeli nie posiadasz jeszcze konta <a href="login.php?id=1">zarejestruj się </a></div>'<?php
}
}
form check
function werfikuj(){
$login=$_POST['login'];
$haslo=$_POST['pass'];
$zapytanie= 'Select * from users where login="'.$login.'" and haslo="'.md5($haslo).'"';
$result = $this->db->query($zapytanie);
if($result->num_rows==1) { echo "Zalogowano poprawnie";$row = $result->fetch_assoc(); $_SESSION['login']=$row['id']; $_SESSION['nick']=$row['login']; $_SESSION['power']=$row['power'];}
else { die(json_encode('zly login lub haslo'));}
}
Thx for help.
Ajax does not know you want to show an error, to the ajax call, your "Zalogowano poprawnie" message and encoded 'zly login lub haslo' message is as meaningless as to me ( I don't know your language). If you want to tell ajax it is an error, you need to response with a different http response code. the 'failed' method is call only when there's a HTTP error response.
If you are using PHP5,
echo json_encode('zly login lub haslo');
http_response_code(404);
exit();
By the way, I don't know your intent in using json_encode. This might not eventually solve your problem. But I believe it answers why you are not getting 'error'
Alternatively, you can always return just a 'ok' or 'failed' message back. Ajax will always call the 'done' method. Inside the 'done' method, you trigger different action according to the message ('ok' or 'failed')