简体   繁体   中英

500 internal server error using jquery and ajax in laravel 5.2

I am building edit post system using jquery and ajax in laravel 5.2. When i click on save changes button in my bootstrap modal, the following error is displayed:

Error: POST http://localhost:8000/edit 500 (Internal Server Error)

send @ jquery-1.12.0.min.js:4

ajax @ jquery-1.12.0.min.js:4 (anonymous function) @ myplace.js:24

dispatch @ jquery-1.12.0.min.js:3

r.handle @ jquery-1.12.0.min.js:3

js code:

$('#modal-save').on('click' , function() {

 $.ajax({

 method : 'POST' ,
 url : url ,
 data: { body: $('#post-body').val(), postid: '' , _token: token }})

.done(function(msg) {

console.log(msg['message']);

    });
  });

Included in view file:

    <script>
    var token='{{ Session::token() }}';
    var url='{{  route('edit') }}' ;
  </script>


 <script   src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

 <script   src="https://code.jquery.com/jquery-migrate-1.2.1.min.js" ></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
  <script src="src/js/myplace.js"></script>

It seems like you have problems with our csrf token. Before making your ajax calls just change your ajax setup and put the token in every header you sent via ajax. This should fix your error.

First add a meta tag

<meta name="_token" content="{{ csrf_token() }}">

Then adjust ajax setup

$(function () {
    $.ajaxSetup({
        headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
    });
});

or even simpler

$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });

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