Here is the workflow:
Starts with root_page.js
document.addEventListener('DOMContentLoaded', function() {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function (data) {
// code
};
httpRequest.open('GET', '/contents/ajax_rss.js', true);
httpRequest.send();
})
This sends ajax request which is successfully routed to contents#ajax_rss
def ajax_rss
respond_to do |format|
format.js {
}
end
end
And should render the following ajax_rss.js.erb
document.getElementById("rss").innerHTML = "HELLO WORLD!";
Here's the server response:
Processing by ContentsController#ajax_rss as JS
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = ?
ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
Rendering contents/ajax_rss.js.erb
Rendered contents/ajax_rss.js.erb (1.1ms)
Completed 200 OK in 9ms (Views: 5.0ms | ActiveRecord: 0.9ms)
But the text is not displayed accordingly. What am I missing? This is my first attempt at AJAX when not called from a form or button using remote: true.
All remote: true calls work as expected.
remote: true
option enables client side to execute the js returned from the server.This is the part you need to fix.
You can pass the response to eval(response)
. Refer: Calling a JavaScript function returned from an Ajax response
You can do it using eval:
request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (request.readyState == 4 && request.status == 200)
{
eval(request.responseText);
}
};
request.open('GET', '/contents/ajax_rss.js');
request.send();