Reputation: 123
I can't seem to figure out why this is not working or find a relevant article. I can see the json object in firebug return either success: false or success: true from the post request so i don't know why the function won't fire.
ajax
$("#login").submit(function (e) {
e.preventDefault();
$.ajax({
url: "../process/login-process.php",
type: "POST",
contentType: "application/json; charset=utf-8",
data: { 'username': $('[name=username]').val(), 'password': $('[name=password]').val() },
beforeSend : function (){
//$("#login").hide();
},
success: function(data){
window.localation=data.redirect;
},
error: function(data) {
$(".error").html('');
alert('wtf');
if(data.empty) {
$(".error").html(data.empty);
}
if(data.incorrect) {
$(".error").html(data.incorrect);
}
}
});
});
php
<?php
session_start();
include "../inc/connect.php";
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$password = hash('sha256', $password);
$sql = "SELECT * FROM admin WHERE username ='$username' AND password ='$password'";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
$row = mysqli_fetch_array($result);
$count=mysqli_num_rows($result);
if ($username == "" || $password == "") {
$data['empty'] = 'All fields are required.';
} else if(($count==1) && ($username)) {
$_SESSION['user'] = $row['firstName'];
$_SESSION['userID'] = $row['adminID'];
$data['success'] = true;
$data['redirect'] = '../pages/dashboard.php';
} else {
$data['success'] = false;
$data['incorrect'] = "Incorrect Username or Password.";
}
echo json_encode($data);
?>
Upvotes: 0
Views: 316
Reputation: 3034
There are two things which you need to correct in your code,
window.localation
to window.location
in success
callbackdataType: 'JSON'
in ajax request or use $.parseJSON
in success callbackSo, your success callback should be:
success: function(data){
data = $.parseJSON(data); // <- Don't use this if you add dataType: 'JSON' in ajax
window.location=data.redirect; //<- Spelling corrected for location
}
Upvotes: 1
Reputation: 6393
you are sending a string(in this case, a json) without any header mentioned. so it will always be 200 ok.
hence, error will never fire.
success: function(data){
window.localation=data.redirect; <----- error here. location
},
that's why nothing is happening.
to fire the error in case data is incorrect
instead of:
} else {
$data['success'] = false;
$data['incorrect'] = "Incorrect Username or Password.";
}
use
} else {
header('HTTP/1.0 403 Forbidden');
echo 'Incorrect Username or Password.';
exit;
}
this will give you a 403 forbidden message.
Upvotes: 0