Search code examples
ajaxwordpresswordpress-rest-api

How to access form object from wordpress rest api


I am using this ajax call params to pass data:

var formData = new FormData();

formData.append('file', selectedFile);
formData.append('subject', 'test subject');
formData.append('message', 'test message');

url: 'my/endpoint',
type: 'POST',
data: formData,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false

Here is my endpoint:

function test_endpoint(WP_REST_Request $request){
   return $request->get_body();
   //return wp_mail( $to, $subject, $body, $headers, $attachments );
}

I can see the data:

enter image description here

So basically I am trying to access the form parameters so I can put them into an email. I can't figure our how to access file, subject and message?


Solution

  • I found out that it was my ajax. So I switched to straight XHR and it worked:

     var xhr = new XMLHttpRequest();
     xhr.open('POST', 'my/endpoint', true);
     xhr.onload = function () {
        console.log('response',JSON.parse(this.responseText));
     };
    xhr.send(formData);