Home > OS >  how to handle redirect in laravel when using ajax
how to handle redirect in laravel when using ajax

Time:06-09

im using ajax in laravel

im using a custome request and a custom middleware for authentication

as u know my authentication middleware will redirect a user if user not loged In

but when im using ajax i dont know how to handle this situation i wrote this jquery function which is work correctly

function addBasket(url) {
    var formData = {
        product_id: $("#addbasket").attr('value')
    }
    $.ajax({
        data: formData,
        url: url,
        type: 'POST',
        dataType: 'json',
        success: function (data) {
            data.forEach(el => {
                $("#count").text(el.count)

            })
            console.log(data);
        },
        error: function (error) {
            alert('fail')
            console.log(error)
        }
    })
}

the above code will send request if user loged in but sometimes when user is not loged In obviously it will get error for log which i dont know how i can catch it and handle it

any help will b appreciate

CodePudding user response:

Simply you can redirect if ajax throw any error :

error: function(xhr, status, error) {
   window.location = '/login';
}

You can specified the error code :

error: function(xhr, status, error) {
   if (xhr.status == 401) {
       window.location = '/login';
   } elseif (xhr.status == 419) {
       window.location = '/';
   }
}

CodePudding user response:

If your js code in blade file redirect to your specific route

...

error: function (error) {
    location.replace("{{ route('your_route_name') }}")
}
  • Related