Hello!

I am trying to add some google analytic goal tracking code to various forms for a 3rd party SEO company.

In my custom module I have the following in a hook_form_alter:

$form['#attributes']['onsubmit'] = "_gaq.push(['_trackEvent', 'Product Pages', 'Clicked', 'Add to Cart – ".$form['node']['#value']->title."']);";

It works, however all the single quotes turn to: & #39; and no amount of escaping seems to fix that. :

onsubmit="_gaq.push(['_trackEvent', 'Product Pages', 'Clicked', 'Add to Cart – Product ABC']);">

I suspect its some security measure, but I was wondering if there is any way to get this working. I need variables from within the form, so I don't really want to try a docready solution.

Anyone know? thanks!

Comments

nevets’s picture

A couple approaches

There is a PHP version of google analytic code. I would consider using it and adding a submit handler and doing things server side. Note it required PHP 5.3+.

Or you could create a javascript using Drupal behaviors that handles the submit. Add the file in your hook_form_alter(). The script would find the title field in the form and make the call to _gag.push().

And you are correct, you are running into a security measure.

orkideh’s picture

umm,
if you want to add some js to your form or form element, it is not right way.

try some thing like this :

 $form['#attached']['js'][] = drupal_get_path('module', 'your_module') . '/your_file.js';

and if you want to listen to form submit you can use jquery by listening to submit event

jaypan’s picture

Or, in the same manner, you can add it inline:

$form['#attached']['js'][] = array
(
  'type' => 'inline',
  'data' => 'alert("inline js executed")',
);

Contact me to contract me for D7 -> D10/11 migrations.

heine’s picture

Converting ' and " to entities will prevent them from being interpreted as special (end / start attribute values) by the HTML parser. The entities will not be seen by the JS engine; normalized values will be passed instead.

leevh’s picture

Thanks everyone, it appears Heine is correct that this is not causing an issue with the end result. It appears the real trouble was the form not actually submitting likely due to an ajax addon module. The other answers should come in very handy for trying to fix this issue.

thanks to everyone!