skip to Main Content

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

2

Answers


  1. 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 = '/';
       }
    }
    
    Login or Signup to reply.
  2. If your js code in blade file
    redirect to your specific route

    ...
    
    error: function (error) {
        location.replace("{{ route('your_route_name') }}")
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search