0

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?

2
  • Are you sure you are reaching the right route? and what kind of error are you getting? Commented 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 explorer Commented Oct 20, 2010 at 12:16

1 Answer 1

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.

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

3 Comments

Robbie thanks but could you help me regarding this code(which sent by me) this is my viwe for this controller
<h1>File Upload </h1> <%= form_tag ({:action => 'uploadFile'},:multipart => true) %> <p><label for="upload_file">Select File</label> : <%= file_field 'upload', 'datafile' %></p> <%= submit_tag "Upload" %>
AMIT, I would recommend viewing some of the railscasts for dealing with javascript: railscasts.com/episodes?search=RJS

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.