XMLHttpRequest empty body with laravel [closed]

38 viewsajaxjavascriptlaravelphpxmlhttprequest
0

I’m using XMLHttpRequest to make requests to an api on my PHP server using Laravel.

And I’m having a problem when I use XMLHttpRequest with the POST method to send the data to the server, and for some reason an empty body is arriving in PHP, which is the payload of the request.

The code is something simple:

// Create a new FormData object
const formData = new FormData();

// Add the form fields to the FormData object
formData.append('title', 'testesdsf');
formData.append('file', fileInput.files[0]); // Assuming that fileInput is the file input in your form

// Create a new XMLHttpRequest request
const xhr = new XMLHttpRequest();

// Set the request URL and method
xhr.open('POST', '/your-route', true);

// Set the Content-Type header to multipart/form-data
// This is not strictly necessary, but it is good practice
xhr.setRequestHeader('Content-Type', 'multipart/form-data');

// Set the callback function for the response
xhr.onload = function() {
   // Check if the request was successful
   if (xhr.status >= 200 && xhr.status < 300) {
     // Process response here
     console.log(xhr.responseText);
   } else {
     // Handle request errors
     console.error('Request error:', xhr.status);
   }
};

// Send the request with the FormData data
xhr.send(formData);

My route em PHP, I’m not using any middleware just a simple route, I’ve already done the tests using routes such as API and WEB but it didn’t result in anything:

Route::post('jobs', [Jobs::class, 'onCreateOrUpdate']);

My controller:

 public function onCreateOrUpdate(): JsonResponse
    {
        try {
            // $this->employeeLogged();
            // $this->validatePermission(JobPermissions::JOB_REGISTER);
            $this->createOrUpdate();

            return $this->responseOk();
        } catch (Throwable $th) {
            return $this->responseException($th);
        }
    }

    private function createOrUpdate(): void
    {
        $request = request();
        trace_log(json_encode($request->all()). "  || TITLE : ". json_encode(Input::all()));

        // $job = Job::updateOrCreate(
        //     ['id' => $request->input('id')],
        //     $request->all()
        // );

        // $this->response['data'] = $job;
    }

Log result:

[]  || TITLE : []

Inspection network:

------WebKitFormBoundary5TlsoKtskQwGC0Zw
Content-Disposition: form-data; name="title"

testesdsf
------WebKitFormBoundary5TlsoKtskQwGC0Zw
Content-Disposition: form-data; name="_method"

PUT
------WebKitFormBoundary5TlsoKtskQwGC0Zw

Researching this problem I found some answers, which talked about adding a _method parameter and sending PUT, PATCH, etc.
I tested them all and had no results. I don’t know what else I can do anymore.