Skip to content

HTTP requests with Javascript

Thomas Starzynski edited this page Sep 2, 2019 · 7 revisions

Custom HTTP requests with javascript

In your JS

// grab the encoded authenticity token
const authenticityToken = document.querySelector('[name="csrf-token"]').content;

// send custom Post Request
const sendPostRequest = () => {
  const xhr = new XMLHttpRequest();
  
  // whenever the request gets a response the .onload() function gets triggered
  // its like an event listener
  xhr.onload = function () { 
    console.log(this.responseText);
  };

  // DATA TO SEND
  const toSend = {
    authenticity_token: authenticityToken,
    feedback: {
      content: TODO
    }
  };
  xhr.open("POST", "/feedbacks");
  xhr.setRequestHeader("Content-type", "application/json");
  xhr.send(JSON.stringify(toSend));
  // console.log("POST request send with data: ");
  // console.log(toSend);
  // REDIRECT USER AFTER POST REQUEST IF YOU NEED TO
  // window.location = <REDIRECTION-URL>
};

In your controller

# feedbacks_controller.rb
def create
  # now you can acces the send data and process it!
  params[:feedback][:content] 
  render json: { msg: "this will be recieved from by the onload() callback function inside JS" }
end

In your VIEW (DEPRECATED)

authenticity token gets encoded by rails by default! But if you want to encode it yourselfe thats how you could do it:

<!-- yourpage.html.erb -->
<input id="auth" type="hidden" value="<%= session[:_csrf_token] %>">

Clone this wiki locally