MaDaHoPe MaDaHoPe - 6 months ago 15
PHP Question

Ajax request shows JSON after success

I am trying to do a simple login through

AJAX
and it works fine except that after the success callback alerts the response, the browser shows the
JSON
response like this:


{"status":"success","username":1234}


I have used the same piece of code several times before with no problems, but I think I am missing some knowledge as to why this is happening? There are some modifications of course, but the
AJAX
part is the same in both
PHP
and
Jquery
and I can't figure out what I am doing wrong.

This is the Jquery:

$('#btnLogin').on('click', function(){
login();
});

function login(){
var un = $('#loginUn').val();
var pwd = $('#loginPwd').val();

$.ajax({
url: 'index.php?page=login',
type: 'POST',
dataType: 'json',
data: {'un': un, 'pwd': pwd},
success: function(data){
alert("You are logged in as "+data.username);
},
error: function (request, error, data) {
console.log(arguments);
alert(" Can't do because: " + error+ " DATA: " + data);
}
});


}

The PHP controller:

include_once 'models/login.class.php';
$user = new Login( $dbh );


// If the form is submitted
if(isset($_POST['un'])){

// Check if fields are empty
$fields = array('un', 'pwd');

$error = false; //No errors yet

//Loop trough each field
foreach($fields AS $fieldname) {
if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
$error = true; //Yup there are errors
}
}
// If there are no errors
if(!$error) {
$un = $_POST['un'];
$pwd = $_POST['pwd'];

$user->checkUser($un, $pwd );
}
}
$view = include_once"views/login-html.php";
return $view;


And finally the model generating the response:

class Login {
private $dbh;

// Connect to database
public function __construct ( $pdo ) {
$this->dbh = $pdo;
}

public function checkUser ($un, $pwd ){
$sth = $this->dbh->prepare('SELECT password, username FROM employees WHERE username = ?');

$sth->execute(array($un));

//Getting the data from db
while($r=$sth->fetch()){
$password = $r['password'];
$username = $r['username'];
}

if($un == $username && $pwd == $password){

$array = array('status' => 'success', 'username' => $username);
// echo "<script>alert('You are logged in as ".$username."');</script>";
// echo "<script>window.location.href='index.php';</script>";
// echo json_encode(array('status' => 'success', 'username' => $username);
$forEcho = json_encode($array);

echo $forEcho;
}else{
echo json_encode(array('status' => 'failure'));
}
exit;
}// End checkUser function
}// End of class


This is the HTML:

<div class="container text-center">
<div class="col-sm-4 col-sm-offset-4">
<h1>Login</h1>

<form role="form" method="post">

<div class="form-group">
<div class="row">
<h3>Username</h3>
<div class="input-group">
<div class="input-group-addon">
<span class="fa fa-user"></span>
</div>
<input type="text" name="un" class="form-control" id="loginUn" placeholder="Please type in your username">
</div>
</div>
</div>

<div class="form-group">
<div class="row">
<h3 id="lblPassword">Password</h3>
<div class="input-group">
<div class="input-group-addon">
<span class="fa fa-key"></span>
</div>
<input type="password" name="pwd" class="form-control" id="loginPwd" placeholder="Please type in your password">
</div>
</div>
</div>

<button id="btnLogin" type="¨button" name="btnLogin" class="btn btn-success">Submit</button>

</form>
</div>
</div>


If somebody could tell me where I am going wrong I would really appreciate it! Have been looking for a solution/explanation with no result for several hours.

EDIT: Added the HTML. The alert in the success callback works just fine, but when closing it the JSON is all that is displayed on a blank screen. Never had this happen to me before.

Answer

You have an invalid value for the type attribute:

type="¨button"

… so the button reverts to the default and is a submit button.

You are seeing the results of submitting the form normally instead of using Ajax.

As a short term fix, remove the ¨. In the long term, you should adopt unobtrusive JavaScript as a best practise.