0

I m new in Jquery and Ajax.... What i want to do is.. I have a controller action which reads a file content and stores it in a variable. I want to pass file name from jquery and want to access that file content through variable in jquery and display it in a div tag. For this i have used this code in controller...

requests_controller.rb

def download
   IO.foreach "#{RAILS_ROOT}/Backend/History/#{params[:filename]}" do |line|
      @file_content << line
      @file_content << '<br/>'
   end 
end

Code in Jquery is...

jQuery("#play").click(function() {
    jQuery.get("/requests/download_log", { filename: filename});
});
2
  • Are you looking to store a variable in javascript and then manipulate that somehow? If so; stackoverflow.com/questions/3155090/… Commented Dec 12, 2012 at 11:07
  • Not directly related to your question, but your file name related code is very dangerous. It allows aribitrary file names to be injected and thus can be used to download almost any file, for example the filename parameter ../../config/database.yml would download your database configuration file, including any passwords you might have stored in there. Commented Dec 12, 2012 at 12:40

1 Answer 1

0

Its not clear what you are trying to do. Do you want to access the controller variable into the jquery view, or do you want from an ajax jquery function request a controller action and get some data from the response?

I think you want to do the first thing, so you can do on the controller:

class MyController < ApplicationController
  def my_action
    @file_content = some_content
  end
end

On the view my_action.html.erb

<script type="text/javascript">
  $(document).ready(function() {
    $("#play").click(function() {
      $.get("/requests/download_log", { filename: <%= j @file_content %> });
    });
  });
</script>

Now if by chance you want to do the second thing I said, you can do

class MyController < ApplicationController
  def download_log
    @file_content = some_content
    respond_to do |format|
      format.json { render json: @file_content.to_json }
    end
  end
end

and on the view

success_handler = function(json_data) {
  // Do any operation with the json_data 
}

error_handler = function(jqXHR, textStatus, errorThrown) {
  // Handle ajax errors here
} 

$("#play").click(function() {
  $.ajax("/requests/download_log.json", dataType: "json",  success: success_handler, error: error_handler);
});
Sign up to request clarification or add additional context in comments.

Comments

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.