Steve Steve - 2 months ago 8
Ajax Question

Alert not appearing if i put the route under auth middleware group

I am not allowing the user to submit the form if not logged in. So, giving the alert to login.


Jquery and Ajax

$(document).on('submit', '.bet', function (e)
{
e.preventDefault();
var frm = $(this);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
dataType: 'json',
success: function (data)
{
if(data == 'notloggedin')
{
alert('You must login first!');
}
else if(data==true)
{
swal('Bet Success! The details has been sent to your email!');
}
else if(data=='dateexpired')
{
swal('The match bet time expired!');
}
}
});
});


Controller:

public function store(Request $request)
{
if($request->ajax())
{
if(!Auth::check())
{
echo json_encode('notloggedin');die;
}
....


This went all good. But, if I put this route under auth middleware the alert is not appearing. And in the developer's tool i see
unauthorized action
. Yes. it is obvious but i still want the alert to appear.

Route::group(['middleware' => ['auth']], function () {
Route::post('/bet/store','BetController@store');
});

Answer

The Error is not shown because if the auth middleware fails the response indicates that the request was not successful ( so success method gets not executed ). In this case you have to use .fail() method.

    var jqXHR = $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            dataType: 'json',
            success: function (data)
            {
                if(data == 'notloggedin')
                {
                        alert('You must login first!');
                }
                else if(data==true)
                {
                        swal('Bet Success! The details has been sent to your email!');
                }
                else if(data=='dateexpired')
                {
                      swal('The match bet time expired!');
                }
             }
     }); 

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {
   if(jqXHR.status == 401) {
     alert('unauthorized');
   } 
});