Skip to main content
AvalancheWHO
Participant
March 28, 2012
Question

ToScript Output. CF >JS

  • March 28, 2012
  • 3 replies
  • 1375 views

I'm having some trouble passing a variable from Coldfusion to Javascript.

There are two defined session varaibles which work fine with the ToScript but fail when I try and use them inside the javascript.

<cfset session.ga_usersecret = "testGAUS" />

<cfset session.AIsession = "testGAS" />

<script type="text/javascript">

<cfoutput>

var #toScript(session.ga_usersecret, "GAuser")#

var #toScript(session.AIsession, "GAsession")#

var _gaq = _gaq || [];

_gaq.push(['_setAccount', 'UA-XXXXXX']);

_gaq.push(['_trackPageview']);

_gaq.push(['_setCustomVar', 1,'ID','GAuser',1]);

_gaq.push(['_setCustomVar', 2,'Segment','GAsession',2]);

</cfoutput>

</script>

Viewing the page source shows that the toScript works fine but it's not recognising the varaibles later in the script. Any ideas how to get the JS to output the varibale values?

Thanks in advance.

This topic has been closed for replies.

3 replies

BKBK
Community Expert
Community Expert
March 28, 2012

AvalancheWHO wrote:

_gaq.push(['_setAccount', 'UA-XXXXXX']);

_gaq.push(['_trackPageview']);

_gaq.push(['_setCustomVar', 1,'ID','GAuser',1]);

_gaq.push(['_setCustomVar', 2,'Segment','GAsession',2]);

What's the idea of 'pushing' whole arrays? I expected you to be pushing one element at a time into an array, like this

var _gaq = ['_setAccount', 'UA-xxxxxx']; // initial array

// subsequent elements pushed into array

_gaq.push('_trackPageview');

_gaq.push(GAuser);

_gaq.push(GAsession);

Inspiring
March 28, 2012

Putting quotes around the name of a variable often produces unexpected results. 

To troubleshoot this, the first thing I would do is output the js variables into an alert right after I create them.

AvalancheWHO
Participant
March 28, 2012

I've stripped the quotes out in the JS and am now running an alert directly after the toScript commands.

New Code:

<cfset session.ga_usersecret = "testGAUS" />

<cfset session.AIsession = "testGAS" />

<script type="text/javascript">

<cfoutput>

var #toScript(session.ga_usersecret, "GAuser")#;

var #toScript(session.AIsession, "GAsession")#;

alert('GAuser ' + GAuser + ' AND GAsession ' + GAsession);

var _gaq = _gaq || [];

_gaq.push(['_setAccount', 'UA-xxxxxx']);

_gaq.push(['_trackPageview']);

_gaq.push(['_setCustomVar', 1,'ID', GAuser,1]);

_gaq.push(['_setCustomVar', 2,'Segment', GAsession,2]);

</cfoutput>

</script>

The alert displays the variables correctly but they are still not being called into the _gaq.push.

Owainnorth
Inspiring
March 28, 2012

Right, ignore all the ColdFusion stuff - is the JS in the page source valid? If you just put it in a static page and run it, does it work?

Participating Frequently
March 28, 2012

It looks like you're not using the variables in your push functions; you're

sending strings. Try this, maybe:

_gaq.push();

_gaq.push();