title: PHP/Javascript Validated Calculation
body: <p>I have come across this problem before and expect to do so again: I want to run a subtotal calculation in both javascript and PHP. I may want to change the calculation at some point.</p>
  
  <ul>
  <li>It needs to run in javascript to maximise the speed of the calculation, so that the user knows what to expect.</li>
  <li>It needs to run in PHP so that I am getting a valid subtotal which a malicious user cannot interfere with.</li>
  </ul>
  
  <p>As such:</p>
  
  <ul>
  <li>If I only run the calculation on the client-side (in javascript), a malicious user may hack the javascript and change the subtotal.</li>
  <li>If I only run the calculation on the server-side (in PHP), an AJAX call would have to be waited on for the user to get their updated subtotal.</li>
  </ul>
  
  <p>So I want to perform the calculation on both sides. The only way I have seen this done is by programming the calculation in PHP and programming the calculation in separate javascript.</p>
  
  <p>My <strong>question</strong> is, what pattern, technique or technology would people recommend that I use to create the calculation on the server-side and make it compatible with javascript when it is sent to the client-side?</p>
  
  <p>An idea I had, for example, was a PHP array for the calculation, which gets translated into PHP code and javascript code, e.g:</p>
  
  <pre><code>array(
      array(type =&gt; "operand", "name" =&gt; "variable_A"),
      array(type =&gt; "operator", "name" =&gt; "multiply"),
      array(type =&gt; "operand", "name" =&gt; "variable_B"),
  )
  </code></pre>
  
  <p>This might convert into PHP:</p>
  
  <pre><code>return $variable_A * $variable_B;
  </code></pre>
  
  <p>And into Javascript:</p>
  
  <pre><code>return variable_A * variable_B;
  </code></pre>
  
  <p>That's an example operational pattern. I don't know what real ones would look like if they exist.</p>