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

moctarss's avatar

How to post a data using Plain Javascript fetch on Laravel?

I made this method on my javascript to post data into my database:

if(document.getElementById('approve_leave_request')){
        document.getElementById('approve_leave_request').addEventListener('click', ()=>{
            const urlReq = window.location.origin+"/leave/customize";
            const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
            
        const leave = {
                status: 'Approved',
            };

            const request = new Request(urlReq, {
                method: 'POST',
                body: JSON.stringify(leave),
                headers: new Headers({
                    'Content-Type': 'application/json',
                    "X-CSRF-TOKEN": token
                })
            });

            fetch(request).then(res => res.json()).then(res => console.log(res));
                    
        })
    }

and this is my controller function:

public function customize_update(Request $request){
        return response()->json(['message'=>'Called successfully.']);
}

and on my api:

Route::post('leave/customize', 'LeaveController@customize_update')->name('api.leave.customize');

but during execution i am getting this error:

POST http://127.0.0.1:8000/leave/customize 405 (Method Not Allowed)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
0 likes
3 replies
moctarss's avatar

Thank you very much. The problem with my code is on my url. It must be window.location.origin+"/api/leave/customize"; instead of window.location.origin+"/leave/customize";

Please or to participate in this conversation.