Pregunta

Attempting to add mixpanel's code into my site. However, I cannot get the javascript in my rails 3 app to track an event when I do an onsubmit for the form. The code does work from the console window of chrome. Any suggestions? Below is the code from my html.erb file. This is placed in the head of the file, along with the provided javascript from mixpanel.

    <% javascript_tag do %>
      var my_term = <%= strip_tags(@term.to_json) %>
<% end %>

Here's the code that I have in my form to track a submit

<%= form_tag("/search", :method => "get", :onsubmit => 'mpq.track("search",{"term":my_term});', :style => "float:right;margin-top:9px;") do %>

Thanks

Generated js

<script type="text/javascript">
//<![CDATA[
      var my_term = "san francisco"

//]]>
</script>

Generated html

<form accept-charset="UTF-8" action="/search" method="get" onsubmit="mpq.track(&quot;search&quot;,{&quot;term&quot;:my_term});" style="float:right;margin-top:9px;">
¿Fue útil?

Solución

There are two issues with your code:

1 - Look at your onsubmit in your generated HTML:

onsubmit="mpq.track(&quot;search&quot;,{&quot;term&quot;:my_term});" 

You are using &quot; when you should be using an actual "

2 - In some cases, even after fixing the &quot; issue, the event will not fire. This is because the page will change before the call to Mixpanel has a chance to resolve. It would be better just to call mpq.track() on the search page itself, instead of using an onsubmit javascript event.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top