I have the following method which allows a user to login into my application:
public function login()
{
if($this->Auth->user())
{
$this->Session->setFlash(__('Already logged in...'), 'default', array(), 'auth');
$this->redirect(array('controller'=>'pages','action'=>'display','home'));
}
if ($this->request->is('ajax'))
{
$this->layout = 'ajax';
if ($this->Auth->login())
{
}
else
{
}
}
else if ($this->request->is('post'))
{
if ($this->Auth->login())
{
return $this->redirect($this->Auth->redirect());
}
else
{
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
It allows a user to login either using a post request or via an ajax request. However with regards to the ajax requests how do I pass the results back using JSON? So for example if the user enters the wrong details pass back an error message?
I have the jQuery AJAX already setup so I just need to do some extra logic in the success method to deal with the return which will either show the error message from the server or do a redirect again based on the return from the server.
e.g.
$('form').live('submit', function (event) {
// Declare the form
var form = $(this);
// Stop the form from doing a native postback
event.preventDefault();
// Get the data from the form
var data = form.serialize();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: data,
success: function (responseHtml) {
// If correct login details
if(success){
window.location.href('INSERT LOCATION TO REDIRECT TO FROM SERVER');
} else {
alert('INSERT MESSAGE FROM THE SERVER');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error!');
}
});
});
Can anyone help? I’m using CakePHP 2.0 and all of the tutorials I have seen on the net and on here have either been outdated or much too long-winded for what I’m trying to achieve.
Edit: you need to use the following php code
on the javascript side you need to modify your javascript to handle json values using jQuery.getJSON. example of jQuery.getJSON is availabe here http://api.jquery.com/jQuery.getJSON/
use this jQuery code