ajax post with laravel 5.6

我们两清 提交于 2021-01-28 06:03:00

问题


I can't figure out how to get this ajax request to post.

     <button class="btn btn-sm btn-primary" id="ajaxSubmit">Submit</button>

      <textarea rows="4" class="form-control resize_vertical" id="application_notes" name="application_notes" placeholder="Notes">{{$application->notes}}</textarea>



<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  var url = "/instructor-notes-save/{{$application->id}}"
      $(document).ready(function(){
         $('#ajaxSubmit').click(function(e){
               e.preventDefault();
               $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
            $.ajax({

                  url: url,
                  method: 'post',
                  data: {
                     application_notes: jQuery('#application_notes').val(),
                  },
                  success: function(response){
                     console.log(response);
                  }});
               });
            });
</script>

My controller is this:

public function saveNotes(Request $request, $id)
    {
      $application = Application::findOrFail($id);
      $application->notes = $request->application_notes;
      $application->save();
      return response()->json(['success'=>'Data is successfully added']);
    }

And for what it's worth, here is my route:

Route::post('/instructor-notes-save/{id}', 'InstructorsController@saveNotes')->name('instructor.save.note');

What am i missing to get this ajax request to work? In my console log, i get a 419 unknown status error.


回答1:


Kindly check that the meta tag _token is present in your layout file inside the <head> tag.

Also please make sure that the AJAX url is present in your routes file.




回答2:


add the following tag in your html <head>:

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



来源:https://stackoverflow.com/questions/50477778/ajax-post-with-laravel-5-6

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