Search code examples
javascripthtmlcoldfusionlucee

Using variable in Javascript to add functionality within cfml tags that call a query


I am looking to use my values from addition and subtraction, from javascript, and use them to increment the startRow and endRow values together. I have the addition and subtraction working, and the value being displayed. Now I cannot figure out how to add the value within the quotes. every time I try to use the ## variable markers, it tells me that my variables do not exist. I want to be able to press the next and Previous button and have it show me the former and latter 20 results. `

<cfoutput>
  <script type="text/javascript">
    var currentValue = 0;
    var add = function(valueToAdd){
      ("adding: " + valueToAdd);
      currentValue += valueToAdd;
      document.getElementById('number').innerHTML = currentValue;
    };
  </script>
</cfoutput>
<cfparam name="url.start" default="1" >
<cfquery name="query" datasource="">

</cfquery>

<table>
  <cfset totalPages = ceiling(query.recordCount)>
  <cfset thisPage = ceiling(url.start)>
  <cfloop query="query"  startRow="1" endRow="20">
    <cfoutput>
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </cfoutput>
  </cfloop>
</table>
<html>
  <head>
  </head>
  <body>
    <div id="text">Results = <span id="number">0</span><div>
    <a href="javascript:add(20)">Plus 20 Results</a>
    <a href="javascript:add(-20)">Minus 20 Results</a>
  </body>
</html>

I removed the database information out of the code.


Solution

  • Given your example code, I don't see why you would need or want to use Javascript in the first place but for the sake of answering the question, the answer is that you cannot directly pass the value of a client-side Javascript variable to a server-side language like ColdFusion. Javascript runs client-side, such as in your browser. ColdFusion runs on a server. Because Javascript runs separately from ColdFusion you must use some means of sending the value(s) from the client side (i.e., a computer with a browser) to the server.

    Possible Options:

    1. Send a value as a URL parameter:

      <a href="https://www.example.com/index.cfm?start=20">Plus 20 Results</a>

      or

      <a href="javascript:location.href='https://www.example.com/index.cfm?start='+add(20)"/>Plus 20 Results</a>

    2. Send a value as a POST or GET parameter via an HTML FORM:

      <form action="/index.cfm" method="post"> <input type="text" name="start" value="20"/> <input type="submit"/> </form>

    3. Or send a Javascript value using POST or GET with AJAX to a ColdFusion service.