Ajax delete not working in laravel 5.2

十年热恋 提交于 2019-12-14 03:26:31

问题


I'm trying to delete a record in mysql in laravel application. But it shows TokenMismatchException error. I am not able to find why its throwing error. It would be great if anyone can help out..

here's view code: (I don't have a form)

<a href="{{url('/page/'.$Ids->id)}}" class="remove-entry">
  <button type="button" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></button>
</a>

And here's jQuery AJAX call:

$(document).on('click', '.remove-entry', function(e){
    e.preventDefault();

    $.ajax({
        url: this.href,
        type: 'DELETE',
        data: {
            "_token": "{{ csrf_token() }}"
        },
        success: function(res) {
            console.log('removed');
        }
    });
});

UPDATE

I tired the following code but it doesn't work probably because it needs to have value token which I suppose is to be fetched from form. But as I already mentioned above, I DON'T have a form set-up. So how can I put the token value in that case?

headers: {'X-CSRF-TOKEN': token}

I understand the problem I'm facing is not new or unique, but it surely is different from the questions that it is supposedly considered duplicate of. Also, the code worked fine earlier but its creating issues in new project


回答1:


If you want to send Ajax Request without CSRF token in laravel.
Goto : app/Http/Middlewares/VerifyCsrfToken.php

protected $except = [
    'request/send_ajax',  /// Enter your route post link here
    'request/send_ajax1'
];

Now you can post ajax request without token

OR

Simple insert a META tag on the page where you will do the Ajax request and default middleware will check for csrf_token.

OR

$.ajax({
        url: "<?php echo url("yourrequest"); ?>",
        type: "POST",
         headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        data:'column='+column+&id='+id,
        success: function(data){
            console.log(msg);
        }        
   });

Work on Laravel5.2




回答2:


Probably you need to generate app key, type in your cmd:

php artisan key:generate

Then write the following line (with the generated key) to the .env file

APP_KEY=your_key

If this not works you may create in your view js variable:

var token = '{{Session::token()}}';

And then instead of using header try:

$.ajax({
          method:"post",
          url:yoururl,
          data:{
            _token:token,
          }
 }).done(function(msg) {

});

The third option can be that something is going wrong while your user logs into your app. Then you need to show the login code from controller.

Hope it will help :)



来源:https://stackoverflow.com/questions/39033178/ajax-delete-not-working-in-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!