daveasdf
daveasdf

Reputation: 81

Is it possible to intertwine Javascript and erb?

I would like to do this, but obviously it's wrong. any way to get the ajax return 'cnut' into the erb?

processResults: function (data, params) { 
        // parse the results into the format expected by Select2
        // since we are using custom formatting functions we do not need to
        // alter the remote JSON data, except to indicate that infinite
        // scrolling can be used
        params.page = params.page || 1;
        return {
          results: $.map(data, function(cnut) {
              <% asdf = BandRole.where(band_id: cnut.id).first %>
              <% member = Fan.find(asdf.fan_id) %>
              var band_member = <% member.name %>
              return { 
                text: cnut.name + ", " + cnut.city + " (" + band_member + ")",
                id: cnut.id,
              };  
          }),
          pagination: {
            more: (params.page * 30) < data.total_count
          }
        };
      },

Upvotes: 0

Views: 21

Answers (1)

Cannon Moyer
Cannon Moyer

Reputation: 3174

You can if you tell Rails to render JS instead of JSON.

In your controller setup your respond_to block like this:

respond_to do |format|
  format.html
  format.js { render :your_view }
end

Then create a view named your_view.js.erb. You can use this just like a normal HTML view except you can put your JavaScript and Ruby in this file just like you did in your example. However, this is JS that is sent back to your browser in the response, not JS processing the response. I hope this helps.

Upvotes: 1

Related Questions