1

I want to perform an action do 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 <button id="button" onclick="readfile()" /> 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 do to make fileopen work 
      }
  });
}

routes.rb

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

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

Midori
  • 25
  • 1
  • 10

1 Answers1

3

In answer to your question directly, you have to be able to handle the JS request in the controller. This is typically done by using the respond_to block in Rails, like this:

def fileopen
    respond_to do |format|
        format.js {
            my_file = File.new("public/CHNAME1.txt","w") 
            my_file.write "\tfasf"
            my_file.close
        }
    end
end

This code may give you some sort of a response with your current code, but it might be the case that you need to appreciate better how Ajax & Rails work in order to help you better


How Ajax Works

Ajax is a javascript technology which sends an "asynchronous" request to other pages on your website. By their nature, asynchronous requests are done completely independently of your main HTTP request, and basically act like a "pseudo" browser -- working in the background

Ajax is used to pull data from JS-enabled endpoints (which are handled with the respond_to function in Rails, which you can then use to modify your page in some way. A lot of people get confused with Ajax, but it's actually quite simple -- it's just javascript which pulls data from another page, allowing you to manipulate your page with that data


Using Ajax In Your Views

The reason why this is important for you is because you mentioned you didn't know what to do with the success callback of your app. Hopefully my explanation will show you that the success part of the $.ajax call should be used to append the data you receive from the controller on your page

This can be done in this way:

$("#button").click(function() {
  $.ajax({
      url: "/static_pages/fileopen",
      type: "POST",
      data: {name: $(this).val()},
      success: function (data) { 
          // append data to your page
          $("page_element").html(data);
      }
  });
});
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • thank for your help, but in $("#button").click(function() , i just want when I click that button, fileopen will perform ( write to a text file), can you correct my code in '$("#button").click(function() { $.ajax({ url: "/static_pages/fileopen", type: "POST", data: {name: $(this).val()}, success: function (data) { // append data to your page $("page_element").html(data); } }); });' – Midori Nov 22 '13 at 09:50
  • I want fileopen active when have event onclick button, fileopen will write text to my file. – Midori Nov 22 '13 at 09:55
  • So you want to click button - write text to file - js will load text file & show? – Richard Peck Nov 22 '13 at 09:58
  • no, I don't need load text file & show, I just want that I click button - write text to file. – Midori Nov 22 '13 at 10:00
  • So you don't need it to show on the page? You literally just want to write the text file? – Richard Peck Nov 22 '13 at 10:01
  • Okay, you don't need to worry about your ajax `success` return for that. The real problem will be with the Rails backend (what happens in the controller). I don't have much experience with writing text files directly from the controller, but it seems these guys do: http://stackoverflow.com/questions/5009031/file-open-write-and-save – Richard Peck Nov 22 '13 at 10:09
  • You may wish to try this in your controller (replace your current code): `directory = "../public" File.open(File.join(directory, 'CHNAME1.txt'), 'w') do |f| f.puts "\tfasf" end` – Richard Peck Nov 22 '13 at 10:10
  • oh no, my def : fileopen , is correct, I can write to file when I just call it <%fileopen%>, but what I want is : it only write when I click button. :) – Midori Nov 22 '13 at 10:17
  • Okay, so you say that it works when you call `<% fileopen %>` - where do you put this in order for it to work? In a view? – Richard Peck Nov 22 '13 at 10:19
  • yes, when I put in a view it works, but i don't know how to make it work when I do : < button> id="buttn" onclick= " javascript to call fileopen " , I don't know how to write code of "javascript to call fileopen" – Midori Nov 22 '13 at 10:26
  • 1
    You'd have to call `fileopen` using Ajax, and that would work as I explained. However, I am extremely confused at how putting `<% fileopen %>` in a view performed a controller action? Have you got a helper called `fileopen` somewhere? – Richard Peck Nov 22 '13 at 10:27
  • Oh, you 're right, first, I put def fileopen in helper to make sure that it work, then I put def fileopen in controller to call it by AJAX. But i can't call it by AJAX, I tried code that you write above but it still not work. – Midori Nov 22 '13 at 10:32
  • 1
    Okay, there are a number of potential reasons why it won't work. Firstly, calling a helper is much easier than calling a controller function via JS. The first question I have is - do you have a route set up for `/static_pages/fileopen` ? – Richard Peck Nov 22 '13 at 10:52
  • 1
    Okay good -- is the route POST or GET? Secondly, you have to look at whether the AJAX is firing. You should add an alert after the `.on('click')` event to see if it's actually calling the JS when it's being clicked. After that, we need to see if the Ajax is pinging the controller correctly – Richard Peck Nov 22 '13 at 10:56
  • the route is GET, when alert befor AJAX, it work and alert after AJAX don't work – Midori Nov 22 '13 at 11:02
  • 1
    Okay, that means that the event is firing. Now what you need to do is test if Ajax is actually firing. To do this, in Chrome, right click on the page, select `inspect element` and then go to `Network` tab. Here, you'll see if the Ajax call is being made when you click the button. We need to know if another request is made when you click the button – Richard Peck Nov 22 '13 at 11:05
  • Sorry, my network disconnected. Can you come back tomorrow and we will continue talking about this problem. Thank you so much for all your help I really appreciate it :) – Midori Nov 22 '13 at 12:12
  • Sure! Just post a comment & I will talk – Richard Peck Nov 22 '13 at 12:17
  • I edited the question, can you tell me what do I need to do next ? – Midori Nov 23 '13 at 04:46