Answer the question
In order to leave comments, you need to log in
Why is the POST array empty?
Hello. It is necessary to send an AJAX request in Laravel using the POST method and receive some response from the server. I do this:
1. I create a controller (AjaxController.php) with the following code:
<?php namespace App\Http\Controllers;
class AjaxController extends Controller {
public function request() {
$param = \Request::post('param');
echo json_encode($param);
}
}
Route::post('/ajax/request', '[email protected]');
jQuery.ajax({
url: location.origin + '/ajax/request',
async: false,
type: 'POST',
data: {'param': 32},
dataType: 'json',
success: function(data) {alert(data)},
error: function() {alert('Ошибка')}
});
Answer the question
In order to leave comments, you need to log in
So, the problem was in the missing "X-XSRF-TOKEN" parameter in the request (moreover, that's right, and not "X-CSRF-TOKEN", as one might think). This is one. The second is in the encryption of this parameter, but it was not possible to fully understand it.
With each POST request, this parameter must be passed to the server, so the jQuery code will be like this:
jQuery.ajaxSetup({
headers: {'X-XSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content')}
});
use Symfony\Component\Security\Core\Util\StringUtils;
...
protected function tokensMatch($request) {
$token = $request->session()->token();
$header = $request->header('X-XSRF-TOKEN');
return StringUtils::equals($token, $request->input('_token')) ||
($header && StringUtils::equals($token, $header));
}
one)
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AjaxController extends Controller {
public function request(Request $request) {
if($request->ajax()){
$param = $request->input('param');
echo json_encode($param);
}
}
}
Route::post('ajax/request', '[email protected]');
jQuery.ajax({
url: location.origin + '/ajax/request',
async: false,
type: 'POST',
data: {'param': '32'},
dataType: 'json',
success: function(data) {
alert(data);
},
error: function() {
alert('Ошибка');
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question