Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send GET request to rails from javascript

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

like image 974
hlim Avatar asked Dec 11 '11 07:12

hlim


People also ask

Can you use JavaScript with Rails?

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.

How do you send a request in JavaScript?

You can easily send a http-Request. Just use: HttpRequest("https://example.com", method="post", data="yourkey=yourdata"); That's it!

What is a JS Erb file?

.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.


1 Answers

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!

like image 138
anders Avatar answered Nov 03 '22 00:11

anders