In My controller I am trying to render vanilla JavaScript but am getting an unexpected result. This is the code
class UploadController < ApplicationController
def index
render :file => 'app\views\upload\uploadfile.rhtml'
end
def uploadFile
render :js => "alert('Hello Rails');"
post = DataFile.save(params[:upload])
end
end
Am expecting before executing post = DataFile.save(params[:upload]) I should see a alertbox but I am seeing a download box. What could be the problem?
-
Are you sure you are reaching the right route? and what kind of error are you getting?Elad Meidar– Elad Meidar2010年10月20日 12:09:38 +00:00Commented Oct 20, 2010 at 12:09
-
am not getting any error but when i am trying to render render :js => "alert('Hello Rails');" am getting download box from my explorerAmit Singh Tomar– Amit Singh Tomar2010年10月20日 12:16:51 +00:00Commented Oct 20, 2010 at 12:16
1 Answer 1
render :js will send data with the MIME type text/javascript
Browsers will see this and attempt to download or display it (my browser, Chromium, displays .js files as plaintext.)
render :js is really meant to return some JavaScript that will be processed by code already on that page.
In essence, you can have an AJAX call from jQuery:
$.ajax({
type: "POST",
url: "tokens/1/destroy.js",
data: { _method: 'DELETE', cell: dsrc.id }
});
This is some code taken from a project of mine. Here, no dataType is defined, so jQuery intelligently "guesses" what type of data is returned. It sees that it is MIME-Type: text/javascript and executes it. Which if we were to use your code, would result in an alert dialog being shown.
In essence, you need to have a page already loaded, and the page has to be waiting for the "vanilla JavaScript" to be returned.
If you just want to execute some code for that particular action, you just have to wrap it using javascript_tag in your template/view, or include an external .js file.