Hello. I can not create a working ajax request.
Here is my code:
Button:

<input type="button" id='{{$contractor->id}}' value="Add to favorites" class="btn btn-success" onclick="addToFavourite(this.id)"/> 

Js:

 function addToFavourite(id) { var base_url = 'http://localhost:8000/' $.ajax({ url: base_url+"add-to-favourite", cache: false, data: {'id': id}, // если нужно передать какие-то данные type: "POST", // устанавливаем типа запроса POST success: function (data) { alert('ok') } //контент подгружается в div#content }); } 

Route:

 Route::post('add-to-favourite', 'ContractorsPage@addToFavourite'); 

And controller:

 class ContractorsPage extends Controller { public function addToFavourite(Request $request){ if($request->ajax()) { $data = Input::all(); print_r($data); die; } dd('ok'); } } 

From the button in js id is transmitted, through the alert checked, but further ajax request nothing happens. Please tell me what I was wrong.

Error where in url, as debugger reports:

POST http: // localhost: 8000 / add-to-favorite 500 (Internal Server Error)

  • In the Developer Tools browser tried to watch the answer backend? Share it with him. - xEdelweiss
  • @xEdelweiss, looked, error 500. There was a wrong url. Changed to the correct one, anyway the error: POST localhost: 8000 / add-to-favorite 500 (Internal Server Error). - Valentine Murnik
  • Turn on debugging in Laravel and check again. In the 5th version, you need to set APP_DEBUG=true in the file .env - xEdelweiss
  • I suspect that you have an error due to the lack of a CSRF token. But it is necessary to enable error output and make sure of it - xEdelweiss
  • one
    Try then add the csrf token, or disable its check: CSRF Protection - xEdelweiss

1 answer 1

As written in the comment, the problem with the token. You can solve it like this:

Add to head

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

In function to transfer this token

 function addToFavourite(id) { var base_url = 'http://localhost:8000/' $.ajax({ url: base_url+"add-to-favourite", cache: false, data: {'id': id, '_token': $('meta[name="csrf-token"]').attr('content')}, type: "POST", success: function (data) { alert('ok') } //контент подгружается в div#content }); }