Problem rendering vanilla JavaScript in Ruby – Education Career Blog

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?

,

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.

Leave a Comment