How to fix Unauthenticated error Token in Ajax submit using multiple buttons laravel

Viewed 856

i try to add new items in wishlist user table when click button with ajax . but i get the error {"message":"Unauthenticated."} how to fix that, i use token csrf in head meta but it doesn't work

script JS

function newItem() {
  $('.add-to-wishlist').off('click');
  $('.add-to-wishlist').on('click',function(e) {
     e.preventDefault();
    let product_id =$(this).closest('.actions').attr('data-key');
    let CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content')
    $.ajax({
      url:"/wishlist/add-new",
      type: "post",
      data:{
        _token: CSRF_TOKEN,
        product_id:product_id
      },
      success:function (data) {
       console.log(data.message);
      },
      error:function (data) {
       console.log(data.responseJSON.message);
      },
    });

  });
}

Html

    <meta name="csrf-token" content="{{csrf_token()}}">

 <span class="add-to-links add-to-wishlist"> 
    <a title="Add to Wishlist" href="#!" class="button link-wishlist" >
        <span>Ajouter au Wishlist</span>
    </a>
 </span>

Error

{"message":"Unauthenticated."}
2 Answers

this is because of the __construct method in your controller this method blocks your request because of your middleware if you don't wanna login for running this method do this:

public function __construct()
{
    $this->middleware('auth')->except(['your_method1','your_method2','...']);
}

after doing this, your method can run without login (in auth middleware)

Related