Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Respond with javascript to an HTML request?

Is it possible to respond to an HTML request with javascript? By this I mean that I don't want the page to be refreshed and plus execute some javascript code. I wonder if this is possible by changing only the server side?

In my action, I have something selected to respond to js and html like this:

respond_to do |format|
  format.js
  format.html
end

And I have a .js.erb file that, of course, should be rendered when the browser requests a javascript.

Can this be done? How?

like image 976
fotanus Avatar asked May 21 '13 17:05

fotanus


1 Answers

You cannot do this by only changing the server side code. If you'd like javascript to be executed upon the server's response, then the form will need to be submitted through javascript. This is because javascript will eval the response from the server and run the code.

This can somewhat be trivially added in Rails:

<%= form_for @user, remote: true %>

When it is submitted, then you can send back javascript. For example, to alert that a user was added:

/app/views/users/create.js.erb

alert("user <%= j @user.email %> was added");
like image 64
Jesse Wolgamott Avatar answered Sep 28 '22 14:09

Jesse Wolgamott