1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok that is how you fetch and execute the script. Thank you. Is there any way to pass a variable either to the controller action or the js.erb file itself?
rails "params" hash will still have you GET or POST data, you can use that in the controller or view.
alright I got it working. thanks, mate. May your sword stay sharp and your steed be quick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.