Я столкнулся с проблемой, что не могу передать переменную через AJAX в Laravel Controller.Вот мой код:
Функция AJAX для отправки заказа:
function submitOrder() {
console.log(JSON.stringify(order.positions));
console.log('SENDING ORDER ',order.positions, ' to the database');
event.preventDefault();
// var id = this.id;
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {
'Content-Type':'application/json',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
//FIXME No response
dataType: 'json',
type: "post",
url: '/orders/api/store',
data: {
_method: 'post',
_token: CSRF_TOKEN,
order: JSON.stringify(order.positions)
},
success: function( response ) {
console.log(response);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
}
rout.php
Route::post('/orders/api/store', 'OrdersController@apiStore');
И функция контроллера:
public function apiStore(Request $request) {
$response = [
'request' => $request->order,
'responseText' => 'works',
'status' => '200'
];
return response()->json($response);
}
Ответ, который я получаю:
SENDING ORDER [{…}]0:
{product_id: 3, name: "Мороженое фрукты", price: "45.00", quantity: "1"}
to the database // Sending this array
response {request: null, responseText: "works", status: "200"} //This is the response from Laravel
Как видите, переменная запроса имеет значение null, но это должно быть значение $request->order
, которое было отправлено AJAX.