Skip to main content
November 7, 2009
Question

passing coldfusion variable to javascript

  • November 7, 2009
  • 4 replies
  • 6616 views

I have an external javascript file which I have attached to my page. I want to set some variables in this file to corresponding CF variables.

How can I do this?

I tried:

---------

<html>

<cfoutput>

<head>

<script src="my_own.js"></script>

</head>

</cfoutput>

<body>

</body>

</html>

-----

but the CF code (e.g. #my_variable_name#) inside the my_own.js file remains unchanged.

Any ideas?

Thank you

    This topic has been closed for replies.

    4 replies

    Inspiring
    November 7, 2009

    You can simply rename my_own.js to my_own.js.cfm.  If it's got a .cfm extension, it'll get processed by the CF server being being delivered to the client browser, same as any other request.

    --

    Adam

    ilssac
    Inspiring
    November 7, 2009

    If you make this choice, which is a pretty powerful tool.

    You may want to play with some of the http headers using the <cfheader...> tag.  So that a browser will cache the CFML JS file.  As I understand it, since the extension is not .js, browsers will not cache the file in the same manner.

    BKBK
    Community Expert
    Community Expert
    November 8, 2009
    @Ian Skinner
    a pretty powerful tool.

    Please expand.

    Inspiring
    November 7, 2009

    You can use toScript() or cfwddx to send cf variables to javascript.  Here is an example that uses toScript(),  http://www.pathcom.com/~bracuk/code/RelatedSelects.htm

    BKBK
    Community Expert
    Community Expert
    November 7, 2009
    but the CF code (e.g. #my_variable_name#) inside the my_own.js file remains unchanged.

    Fortunately! Coldfusion variables are defined on the server, Javascript runs on the client. If it were possible to evaluate your variable, you would be able to wreak havoc on client machines.

    I have an external javascript file which I have attached to my page. I
    want to set some variables in this file to corresponding CF variables.

    A possible solution is to evaluate the content of the script, using Coldfusion, and then saving the result as the file my_own.js. Something along these lines

    <cfsavecontent variable="script_content">

    <cfoutput><!--- the JS code containing #my_variable_name# goes in here ---></cfoutput>

    </cfsavecontent>

    <cffile action = "write" output="#script_content#"
       file = "c:\Coldfusion8\wwwroot\scripts\my_own.js">
    November 7, 2009

    I forgot to say that I used firebug to inspect my_own.js after the page was displayed.