I have been trying to implement ajax login with CakePHP 1.3. I have a popup with a simple username/pass login.
Following is in my views/elements/login.ctp:
echo $this->Form->create('User', array('url'=>array('controller'=>'users','action'=>'login'), 'id'=>'user_login'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login'));
Following is in my controller controllers/users_controller.php
public function ajax_login() {
$response = array('success'=>false);
if($this->RequestHandler->isPost()) {
if($this->Auth->login()) {
$response = array('success'=>"true");
} else {
$response = array('success'=>false);
}
}
$this->set('response', $response);
}
The view for the above controller is under views/users/ajax_login.ctp has ONLY this line:
echo $javascript->object(isset($response) ? $response : array());
My Ajax has the following code:
function login_user(){
var username = $("#UserUsername").val();
var password = $("#UserPassword").val();
if(username == "" || username == null || password == "" || password == null){
alert("Please enter a username and password");
return false;
}
$.ajax({
url:"/users/ajax_login",
type:"POST",
data:$('#user_login').serialize(),
dataType:"json",
async: true,
success: function() { console.log("success"); },
error: function(msg) { console.log(msg); }
});
return false;
}
Now, everything seems to be working perfectly, however, this is always failing into the "error" callback and I dont know why. I've read all of the below links on stackoverflow, and none of them seem to be the issue!
Weird JSON behavior when requesting a json file via $.ajax malformed JSON while JSON is valid? Ajax error result with struts2 json_encode creating a malformed JSON (with extra hidden character) php json_encode not returning proper json encoded string
The ONLY thing I suspect is when I read the console.log(msg)
of the error, I get the correct HTML response {"success":true} which is in correct format... BUT... the "responseText" I get something like this:
responseText: "{"success":true}<!-- 0.375s -->"
so basically im guessing it's this "<!-- 0.375s -->" which is causing the json format to always fail in my ajax call. how on earth do i get rid of this?!... I'm no longer sure if this is a CakePHP issue, or and AJAX/JSON issue!... i've worked on both for over 5 years and now im stuck!