javascriptjqueryruby-on-railsajaxruby-on-rails-4

"ActionController::InvalidCrossOriginRequest" error with AJAX request by plain JavaScript


I have code like:

jQuery.ajax({
  url: url  // Some URL
});

The above code worked perfectly. But, I have a requirement to convert this code to pure JS. So, I did:

var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.send();

But, here when the AJAX request is fired I get this error in rails server log:

ActionController::InvalidCrossOriginRequest - Security warning: an embedded tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.

NOTE: I had faced similar error when I passed format: :js in link_to(Fix I referred). But, this happens with pure JavaScript code.

How do I fix this?


Solution

  • Adding xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest"); fixed the cross origin error in rails.

    Now, the code looks like:

    var xhttp = new XMLHttpRequest();
    
    xhttp.open("GET", url, true);
    xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhttp.send();