samedi 25 avril 2015

Rails render partial as widget over ajax using jsonp


I've looked at quite a few other answers on here, but I'm still struggling a bit to figure out how to set up my Rails widget.

I have this code in my widget controller:

  def widget
    status = Company.friendly.find(params[:id]).widget.active
    body = to_json_value(render_to_string('companies/_widget', locals: { profile: self.profile }))

    render json: { status: status, html: body }
  end

  private

  def to_json_value(str)
    str.gsub!("\"", "\\\"")
    str.gsub!(/\n+/, " ")
    str
  end

The self.profile method just sets up a list of variables that get passed to the partial.

What I want to do is give a user a Javascript script tag that they can embed on their (external) website. When a user hits that page, the script will make an AJAX call to the widget controller and if the widget is turned on, it will receive a string of html to be rendered on the page.

So far I've got the widget controller to return a json object with the status and the html string. What I'm wondering is, how do I set up the js file that the user embeds on their page (ideally without relying on jQuery)?

I should note that the widget will show different information depending on what company (Rails model) it belongs to. I was thinking that this might just be pulled in from params like so:

<script src="http://ift.tt/1GuShkN" type="text/javascript"></script>

I'm also not sure where this widget.js.erb script should live in my rails app. Here is what I have so far for my widget.js.erb:

$.ajax({
 type: 'GET',
 url: 'http://ift.tt/1IWFXr0 params[:company] %>/widget',
 data: {
  html: data[key]['html']
 },
dataType: 'json',
  success: function(data) {
    $('#company-widget').html(data.html);
 }
});


Aucun commentaire:

Enregistrer un commentaire