douniani679741 2019-02-02 17:39
浏览 210

Laravel AJAX POST请求失败(500内部服务器错误

I've been stuck with this for hours, checked dozens of examples / StackOverflow answers but I am still getting the same error. It's my first time working with AJAX, but I have a solid amount of experience with Laravel.

The issue I'm getting is a 500 Internal Server Error when trying to send my AJAX request, the aim of which is to update a single row in my database.

I've read that the error is likely caused by the CSRF token not being validated / passed to the back-end, but despite changing my code I am still getting the same issue.

Here is my code:

view.blade.php

<script>

  function likeCandidate(id){
    console.log("Calling like candidate function");
    $.ajax({
      type:'POST',
      url:'/employer/likecandidate',
      data:{
        '_token' : $('[name="_token"]').val(),
        'cand' : id,
        'job' : {{$id}},
        },
           success:function(data) {
    }
  });
  }
</script>
<!-- In the HTML I am including: -->
@csrf

And in my routes I have the post route:

  Route::post('/likecandidate', 'AjaxController@likeCandidate');

And finally in my controller I have the code:

public function likeCandidate(Request $request)
{

  $this->validate($request, [
    'cand'=>'required',
    'job'=>'required',
  ])

  // Find the application
  $application = Application::where('candidateId', $request->input('cand'))
                                 ->('jobId', $request->input('job'))
                                 ->first();

  // Update the candidate's status to liked.
  $application->status = "Liked";
  $application->save();

  // Return status message
  $msg = "Success";

  return response()->json(array('msg'=> $msg), 200);
}

Thanks in advance for any help.

</div>
  • 写回答

1条回答 默认 最新

  • dongyaxiao5884 2019-02-02 18:12
    关注

    Stupid mistake from me here, but I guess I've never used AJAX before so wasn't aware this was an issue. I'm leaving this answer here just in case someone makes the same mistake.

    Check storage/laravel.log to find out the error message when trying to run the function. In my case I had a couple of syntax errors in my likeCandidate function, and this was causing a 500 Internal Server Error (I assumed that the 500 error meant it wasn't able to access the controller.)

    评论

报告相同问题?

悬赏问题

  • ¥15 MapReduce实现倒排索引失败
  • ¥15 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题