简体   繁体   中英

Error 405 Method Not Alowed Exception when post with AJAX with Laravel

I just want to send two variables to my controller with an onclick event in JS, I am using laravel framework and JQuery Ajax.

My onclick call is:

onclick="addArt(<?php echo Session::get("ID") ?>, <?php echo $article->idArticle ?>)"

That goes to a function in my JS sheet:

function addArt(idUser, idArt){
  $.post( "addArt", { IDUser: idUser, IDArt: idArt})
  .done(function( data ) {
      location.reload();
  })
  .fail(function(e) {
      console.log(e);
  });
}

So my route is "addArt" and like always I have the route:

Route::post('addArt',"CarsController@addArt");

Where in my controller I just add the article to the cart with a simple insert of laravel but I get an error 405 (Method Not Alowed).

Can anyone please help me with this?

You get that error because you don't pass to your post object the csrf token.

This will work:

onclick="addArt(<?php echo Session::get("ID") ?>, <?php echo $article->idArticle ?>, <?php echo csrf_token(); ?>)"

and on your function you need to pass the _token value

function addArt(idUser, idArt, token){
  $.post( "addArt", { IDUser: idUser, IDArt: idArt, _token: token})
  .done(function( data ) {
      location.reload();
  })
  .fail(function(e) {
      console.log(e);
  });
}

If you're using Laravel's Blade Templating, you can change a bit and have it work still:

onclick="addArt('{{Session::get("ID")}}', '{{$article->idArticle}}')"
// " " does work inside the {{ }} tags if using Blade.

If you inspect the element now, it should look like this:

onclick="addArt('session', 'article')"

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM