I have the following AJAX call:
$('#FonykerUsernameRegister').blur(function(){
if($(this).val().length > 2) {
alert($(this).val());
$.ajax({
url: '<?php echo $html->url('/fonykers/validate_username',true); ?>' + '/' + $(this).val(),
dataType: 'json',
type: 'POST',
success: function(response) {
if(!response.ok) {
$(this).addClass('error');
error.html(response.msg);
error.fadeIn();
} else {
if($(this).is('.error')) {
alert('im in');
$(this).removeClass('error');
}
$(this).addClass('ok');
}
},
error:function (xhr, ajaxOptions, thrownError){
alert('You fail');
alert(xhr.statusText);
alert(thrownError);
}
});
} else {
error.html('Username must have at least 3 characters');
error.fadeIn();
$(this).addClass('error');
}
});
And this is the method it's calling:
function validate_username($username) {
$this->layout = 'ajax';
$response = array();
$fonyker = $this->Fonyker->find('first', array(
'conditions' => array('Fonyker.username' => $username)
));
if(!strlen($username) > 2) {
$response = json_encode(array('ok' => false, 'msg' => 'Username must have at least 3 characters'));
} else if(!preg_match('"^[a-zA-Z0-9]+$"', $username)) {
$response = json_encode(array('ok' => false, 'msg' => 'Username must be alphanumeric'));
} else if ($fonyker) {
$response = json_encode(array('ok' => false, 'msg' => 'Username is already in use'));
} else {
$response = json_encode(array('ok' => true, 'msg' => ''));
}
echo $response;
}
In the AJAX call it always goes to the error part and outputs that error, and I don't see any whitespaces in my PHP code. Any thoughts?
EDIT:
What was happening is that CakePHP was echoing the entire view in the response, but not really the view but the error screen.
If you need AJAX methods in your controller that do not require a view you must set the $this->autoRender property on the controller method to false before doing anything.