Reputation: 256
I want to working with login system jQuery ajax and json. I'm facing no problem with success function. I dn't know how to through custom errors like "incorrect login".
Here is my code, Please help me.
<script>
$(document).ready(function(){
$("#login").click(function(){
if($("#defaultEmail").val() == ""){
$("#defaultEmail").addClass("field-err");
$("#defaultEmail").focus();
}else if($("#defaultPassword").val() == ""){
$("#defaultEmail").removeClass("field-err");
$("#defaultPassword").addClass("field-err");
$("#defaultPassword").focus();
}else{
$("#defaultPassword").removeClass("field-err");
$('#loading').css('display', 'block');
var email = $('#defaultEmail').val();
var password = $('#defaultPassword').val();
var queryString = "email=" + email + "&password=" + password + "";
$.ajax({
url: 'secureLogin.php',
contentType: "application/json; charset=utf-8",
dataType:'json',
async: false,
type:'GET',
data: queryString,
success: function(data){
$('#loading').css('display', 'none');
var url = "c_profile.php";
$(location).attr('href',url);
},
error: function(request,error){
$('#loading').css('display', 'block');
$("#log-ajax-error").append("ERROR: " + error);
}
});
}
});
});
</script>
Here is my sucureLogin.php code
$email = $_GET['email'];
$password = $_GET['password'];
$encrypted_pass = md5($password);
$sel = @mysql_query("SELECT `name`, `company`, `cid` FROM `company` WHERE `email` = '$email' AND `password` = '$encrypted_pass'");
$count = @mysql_num_rows($sel);
if($count > 0){
while($data = @mysql_fetch_array($sel)){
// Success here
}
}else{
$arr = array('a' => 'Unable to login');
echo json_encode($arr);
}
i'm throwing json_encode for the error. Please help me with this. Thanks in advance.
Upvotes: 1
Views: 1377
Reputation: 25776
On the server side
$arr = array('error' => 'Unable to login');
echo json_encode($arr);
On the client side
success: function(data){
$('#loading').hide();
if( 'error' in data ){
$("#log-ajax-error").append("ERROR: " + data.error);
}
else{
var url = "c_profile.php";
$(location).attr('href',url);
}
},
The error callback will be called if there's an error with the ajax request, so your code needs to be in the success handler.
Upvotes: 3
Reputation: 7374
In ajax, the error handler does not constitute an error thrown by you, it constitutes a connection error, or an error with the request. This means that, no matter how you send back an error response like you have, it will hit the success callback.
In your success you should do some checks for the response:
success: function(data){ if(data.status === false) { // There was an error } else { $('#loading').css('display', 'none'); var url = "c_profile.php"; $(location).attr('href',url); } },
And in your PHP handler add a status key:
$arr = array( 'status' => true (or false), 'a' => 'Unable to login' );
Upvotes: 1