notblakeshelton
notblakeshelton

Reputation: 364

Calling a js.erb file with ajax in ruby on rails

I have the following jQuery function that I'm trying to use with rails to create an alert on a page.

    $("#buttonID").click(function() {
      foo = $("#otherID").val();
      $.ajax({
        submitVar: foo //no idea what to do here
        type: 'GET',
        url: 'controller/action_js',
        dataType: 'script'
      });
    });

in my controller

    def action_js
      @item = Item.find(:name => foo)
      respond_to do |format|
        format.js
      end
    end

action_js.js.erb:

    alert(@item);

I'm trying to make it so that when I click the button with id = 'buttonID', an alert appears showing the item in the database whose name equals the value of the field with id = 'otherID'. I have no idea how to use js.erb properly with ajax or how to pass a variable to my js.erb file. Clicking the button currently does nothing.

Upvotes: 1

Views: 2568

Answers (1)

Rishav Rastogi
Rishav Rastogi

Reputation: 15482

You can use

jQuery.getScript() method to run it. See details, http://api.jquery.com/jQuery.getScript/

or

$.ajax({
    ..., 
    dataType: "script",
    ..
})

Both these above methods will fetch a script and then execute it.

Upvotes: 1

Related Questions