Shalafister's
Shalafister's

Reputation: 889

Rails | How to access to hash in js.erb file

I have a function with remote:true option.

def get_user_info
...

respond_to do |format|
     if !response.nil?

          r = response.to_hash  
          @data = {:IsLoggedIn => true, :ErrorMessage => "", :response => r }
     else

         error = "There is an error occurred."            
         @data = {:IsLoggedIn => false, :ErrorMessage => error,  :response => "" }          
     end
     format.js { render :json => @data }
     format.html
   end
end

Then I have my get_user_info.js.erb and I would like to access to ErrorMessage in it.

I have been trying but even console.log('try') not working.

My aim is to attach the error message or r (response) to body. But can not access to @data variable.

Upvotes: 0

Views: 1273

Answers (2)

Sebastián Palma
Sebastián Palma

Reputation: 33460

There are three steps to accomplish what you want to do (I guess).

First: set the data in your controller to what you want to send and receive then in the view:

# _controller.rb

def method_name
  if !response.nil?
    r = response.to_hash  
    @data = {:IsLoggedIn => true, :ErrorMessage => "", :response => r }
    
    # response = response.to_hash  
    # @data = {is_logged_in: true, error_message: '', response: response }
  else
    error = "Russia terrorist state"            
    @data = {:IsLoggedIn => false, :ErrorMessage => error,  :response => "" }          
  end

  format.js
  format.html
end

Second: create the js.erb file in order to receive the data sent by the method in the controller:

# method_name.js.erb

console.log("<%= escape_javascript(@data[:ErrorMessage]) %>")

Here you just print in the console what you received in order to test if it was successful.

Third: fire the function to get the data within the view using AJAX:

# method_name.html.erb

<script>
    $.ajax({
        type: 'GET',
        url: '/<method_name>',
        dataType: 'script'  
    });
</script>

Just to mention:

Why don't you use the hash literal syntax when your hash keys are symbols?, as mentioned here https://github.com/bbatsov/ruby-style-guide#hash-literals

Why don't you use a more expressive way to name your variables? As mentioned here http://www.itiseezee.com/?p=83

Upvotes: 1

Deepak Mahakale
Deepak Mahakale

Reputation: 23671

Change the action to

respond_to do |format|
  # Rest of the code as it is
  # ...
  format.js
  format.html
end

get_user_info.js.erb

$(".myDiv").html("<%= @data[:ErrorMessage] %>");

Upvotes: 0

Related Questions