mattvv
mattvv

Reputation: 583

Appending Javascript in Rails using AJAX

I have a Javascript where I render a partial using the js.erb:

$('#registration-steps').fadeOut("fast").html("<%= escape_javascript( render :partial =>   @page, :layout => false )%>").fadeIn("slow");

The problem is, in this partial I have some code from adwords I want to render for conversion tracking:

E.g:

<script type="text/javascript" src="https://www.googleadservices.com/pagead/conversion.js">

When I call the partial however, the script is being stripped and the javascript is not being executed.

I tried the following in my js.erb with no avail:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://www.googleadservices.com/pagead/conversion.js";
$("#tracking").append(script);

Upvotes: 1

Views: 499

Answers (1)

twmills
twmills

Reputation: 3015

Try to dynamically execute the script using jQuery's getScript function:

http://api.jquery.com/jQuery.getScript/`

However, that still means that the script include in your partial is mangled when you escape_javascript.

As another possibility you could move the include out of your partial and add a content_for call to your layout:

<% =content_for :ad_words %>

Then at the end of your js.erb file I would insert it:

<% content_for :ad_words do %>
     <script type="text/javascript" src="https://www.googleadservices.com/pagead/conversion.js">
<% end %>

That way there's no longer a chance it will be escaped.

Upvotes: 1

Related Questions