views:

38

answers:

1

Hi all,

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?

+1  A: 

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.

Robbie
Robbie thanks but could you help me regarding this code(which sent by me) this is my viwe for this controller
AMIT
<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
AMIT, I would recommend viewing some of the railscasts for dealing with javascript: http://railscasts.com/episodes?search=RJS
Robbie