Laravel 6 Get information from POST JSON

Viewed 374

I'm trying to get JSON information from POST request. My POST request is:

var money = document.getElementById("code").value;
const Http = new XMLHttpRequest();
const url='/paypal/';
Http.open("POST", url);
Http.setRequestHeader("Content-Type", "application/json");
Http.send(JSON.stringify({
    value: money
}));

And the controller is:

public function paypal(Request $r) {
$postInput = file_get_contents('php://input');
$data = json_decode($postInput, true);
$response = array('value' => $data);
return Response::json($response);
}

but the only result that I get is:

{"value":null}

Any idea where is my problem?

3 Answers

When using POST request dont forget to set csrf token in headers

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

let token = document.head.querySelector('meta[name="csrf-token"]')          
var money = document.getElementById("code").value;
const Http = new XMLHttpRequest();
const url = '/paypal';
Http.open("POST", url);
Http.setRequestHeader("Content-Type", "application/json");
Http.setRequestHeader('X-CSRF-TOKEN', token.content);
Http.send(JSON.stringify({value: money}));

To retrieve the JSON payload from your controller, use:

$data = json_decode($request->getContent(), true);
return response()->json($data);

and make sure variable money have correct value

Thank you guys for your help. I fixed my issue by posting everything through GET request.

For laravel, we can get POST JSON in an easier way.

use Illuminate\Http\Request;


public function test(Request $request) {
    $inputData = $request->json()->all();
}
Related