Reputation: 5662
Below is my AJAX Method which is able to connect to the server:
$.ajax({ type: 'POST', url: $form.attr('action'), data: formData, dataType: 'json', success: function(data){ console.log(data.id); }, error: function(message){ console.log(message.code); } });
Below is the method that i created for cakephp UsersController class that responses to the request:
public function login() { if ($this->request->is('post')) { if ($this->Auth->login()) { return new CakeResponse(array('body'=> json_encode( $this->Auth->user()),'status'=>200)); } else { $reply["code"] = "Invalid username or password and please try again"; return new CakeResponse (array('body'=> json_encode($reply),'status'=>500)); } } }
The issue is, I am unable to read the json response when server sends error. The console.log for the snipped below should write "Invalid username or password and please try again" but it says undefine.
error: function(message){ console.log(message.code); }
However, I am able to read the following:
success: function(data){ console.log(data.id); }
Upvotes: 1
Views: 1794
Reputation: 5692
The parameters of your jQuery error
callback are described here:
So the first argument is the jqXHR
object, described here:
So I guess you can read its responseText
attribute.
error: function(jqXHR, textStatus, errorThrown) {
var message = JSON.parse(jqXHR.responseText);
console.log(message.code);
}
Upvotes: 3
Reputation: 15603
In your below code:
error: function(message){
console.log(message.code);
}
You will get the error that is send by server not that you are trying to get from your code. To read the error from the server side. use the below code:
error: function(message,err,xtr){
console.log(JSON.stringify(message)+" "+err+ " " +xtr);
}
Upvotes: 1