I've been googling all day and still couldn't find any answers.So basically in my javascript function, I want to send a GET request to my rails controller and the rails controller will send back a JSON object. Any idea how do I do this? thnx
If you plan to use Rails with importmap-rails to manage your JavaScript dependencies, there is no need to install Node. js or Yarn. When using import maps, no separate build process is required, just start your server with bin/rails server and you are good to go.
You can easily send a http-Request. Just use: HttpRequest("https://example.com", method="post", data="yourkey=yourdata"); That's it!
.js.erb files are for controller actions, such as create, when you want javascript to be executed when the action completes. For example, when you want to submit a form via ajax and want display an alert when everything is done, you would put the $('#business_submit'). click(...) in your application.
Using jQuery I would do something like this:
In the selector and event you want, for instance on clicking some element:
$(function() { $('#foo').click( function(){ var params = '{"field1": "value1", "field2: "value2"}'; $.get('/controller/bar', params, function(data){ alert(data); }); }); });
Then in your Rails controller:
def bar /// hack hack hack render :json => {"response" => "OK"} end
The in your routes.rb:
match 'controller/bar' => 'controller#bar'
Finally, change "controller" according to your code. Firebug is your friend!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With