1

I want to perform an action write to file in controllers/static_pages_controller.rb:

def fileopen
        my_file = File.new("public/CHNAME1.txt","w") 
        my_file.write "\tfasf"
        my_file.close

    end

(it work well when i define it in helper and call it in view.)

in myview.html.erb, i want some thing like How can I do that? I tried in application.js

function readfile() {
  alert('readfile work')
  $.ajax({
  alert('ajax work')
      url: "/fileopen",
      type: "POST",
      ##don't know what to to to call fileopen
      }
  });
}

routes.rb

match '/fileopen', to:'static_pages#fileopen', via: 'get'

and it's seem nothing happen. Only the first alert work

2 Answers 2

3

You have syntax error, try this:

function readfile() {
  alert('readfile work');
  $.ajax({
      url: "/fileopen",
      type: "POST",
      success: function(){
          alert('ajax work');
      }
  });
}

I don't know ruby but route is on "GET" request and you are making "POST" request:

match '/fileopen', to:'static_pages#fileopen', via: 'get' // should be via: 'post'?
Sign up to request clarification or add additional context in comments.

2 Comments

tks, it helps me a lot , can I send some variable by Ajax, such as function readfile() { alert('readfile work'); $.ajax({ url: "/fileopen", type: "POST", success: function(){ senddata($variable1); senddata($variable2); } }); } and in fileopen I can use def fileopen my_file = File.new("public/CHNAME1.txt","w") my_file.write "$variable1" "$variable2" my_file.close end
You can send data like this: $.ajax({ url: "/fileopen", type: "POST", data: { parameterName: 'parameterValue' } success: function(){ alert('ajax work'); } });. read documentation here: api.jquery.com/jQuery.ajax
2

You can not use alert within ajax, If you want to use it then use in success and error methods

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.