Search code examples
javascriptruby-on-railsajaxxmlhttprequest

Sending "Post" Request to Rails with vanilla JS XMLhttprequest object


I am trying to send a request (in vanilla javascript) from my script file to my backend rails 5 app.

I have been googling and reading MDN, and trying different things, and still can not get it to work. Is anyone able to help with this?

The most recent attempt (below) got this parsing error ActionDispatch::Http::Parameters::ParseError (416: unexpected token at 'object Object]'): However, when I try different formats, I still get errors, so I'm thinking I must be missing something. I have looked at other stack-overflow questions on this, but still get errors when I try to implement their code.

    Wrapping the ajax request in a promise:

    function postRequestPromise(uri) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', uri, true);
        xhr.setRequestHeader('Content-Type', 'application/json', 'Accept', 'application/json');
        xhr.onload = function () {
            resolve(xhr.responseText);
         };
            xhr.onerror = function () {
             reject(xhr.statusText);
        };
       //Ive tried params in several formats:
       //this most recent is giving me a parsing error.
       //my goal is to send JSON to the back-end, to be parsed
       const params = { hello: "hello", world: "world" };
            xhr.send(params);
      });
     }

Then sending the post request:
    postRequestPromise('demo/practice_post')
      .then((replyData) => {
        console.log(replyData);
      })
      .catch((err) => {
        console.log("ERROR:", err);
    });

in the controller, I have tried these things:

    class demo < ApplicationController

      def practice_post

        #all three of these attempts either do not log the body or throw errors:
        p request.body.read
        p request.raw.post
        p params

        render plain: "reached demo#practice_post route"
      end
    end

Thank you for any help!

Solution

  • The part where you send the request with the params, need to be JSON stringified.

    xhr.send(JSON.stringify(params));