Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

jquery - Ajax delete not working in laravel 5.2

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...