Reputation: 449
I have a working dashboard with ajax request. I fire an ajax request on some events which will update a part of the dashboard. But if the session has expired, the part will be refreshed with the login page. How can i do a redirection after the ajax call if the session has expired ?
My ajax call :
$.ajax({
type: "POST",
url: $(this).data('path'),
data: { datas : {
/* some datas */
}},
success: function(data){
$('#mydivtorefresh').html(data);
},
error: function(){
showFlash();
},
});
and my controller :
public function myControllerAction(Request $request)
{
/* some logic */
return $this->render('my/template/toUp.html.twig',array('results' => $results));
All is working well, but if my session expires and i call this ajax request, i will get the login page in the '#mydivtorefresh' instead of a global redirection. I tried with eventListener or with AjaxError callback but with no success. Any help ?
Upvotes: 0
Views: 963
Reputation: 449
Found a working solution :
Add a function in my global controller which check if session is still active and responds with "ok" if yes, "ko" if not.
public function pingAction()
{
$securityContext = $this->container->get('security.context');
if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') || $securityContext->isGranted('IS_AUTHENTICATED_FULLY')) {
return new Response("ok");
}
return new Response("ko");
}
and i check it every times an ajax call is fired using the preFilter jquery event :
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if(originalOptions.data == "CHECKPING"){
return;
}
$.get( Routing.generate('el_ping'), "CHECKPING", function( res ) {
if(res == "ko"){
window.location.replace(Routing.generate('fos_user_security_login'));
}
});
});
Upvotes: 1