Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

marcoB's avatar

Trouble getting data in a Controller through a POST request

Hello !

I am having troubles passing data with a POST request. All i can get is an empty array []. Do you know how to get back the uid variable in the controller ?

Here is my AJAX function :

function new_admin(uid) {
    var request = new XMLHttpRequest();
    request.open("POST", "/add_admin");
    
    request.setRequestHeader('X-CSRF-TOKEN', "{!! csrf_token() !!}");

    request.onreadystatechange = function() {
        if(this.readyState === 4 && this.status === 200) {
            console.log(this.responseText)
        }
    };
    request.send(   JSON.stringify({"uid":uid})    ); //also tried    "uid="+uid
}

and here is my controller (which is "inside" the auth middleware) :

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use \App\Models\Admin;

class AdminController extends Controller
{
	public function store(Request $request){
		return $request->all(); // just for testing : returns []
	}
0 likes
4 replies
Nakov's avatar
Nakov
Best Answer
Level 73

Try adding this line too:

request.setRequestHeader("Content-Type", "application/json");
1 like
marcoB's avatar

@Nakov thanks it was just that ! I may be bad at searching the web ^^, I searched for hours it was painful.

Anyway, thanks a lot for your time @jlrdw and @snapey.

Have a great day.

jlrdw's avatar

What happens if you do a

return response()->json(...

And check the network tab to see what in in there.

Snapey's avatar
request.send(JSON.stringify({uid:uid}));

Please or to participate in this conversation.