Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to combine a javascript value with a php value to a single javascript variable?
    primarykey
    data
    text
    <p>I have a number in php, i.e. <code>25</code>.</p> <p>Then, I have a javascript variable which is a number; i.e. <code>57</code>.</p> <p>The php number is extracted from a text file like this:</p> <pre><code>&lt;!-- NOTE: for this example, the value in file.txt is the number 25 --&gt; &lt;?php $the_number = file_get_contents("file.txt"); ?&gt; </code></pre> <p>And the javascript is like this:</p> <pre><code>/* first let's define "$a_variable_from_somewhere_that_is_a_number" so it helps you understand this question: */ var $a_variable_from_somewhere_that_is_a_number = 57; /* ok and here is the javascript */ var another_number = $a_variable_from_somewhere_that_is_a_number </code></pre> <p>Now, I want to combine these two numbers into a single javascript variable.</p> <p>So I write this javascript:</p> <pre><code>var php_number = parseInt(&lt;?= $the_number ?&gt;); var javascript_number = parseInt(another_number); var combined_number = php_number + javascript_number; </code></pre> <p>And to see if it worked:</p> <pre><code>Did it work? &lt;script type="text/javascript"&gt;document.write(combined_number);&lt;/script&gt; </code></pre> <p>I tried it, but the value is returned as "NaN", meaning it didn't work.</p> <p>So how can I get it to work?</p> <hr> <p><strong>UPDATE:</strong></p> <p>I got it working!! I'm not sure what I did wrong at first because I kept trying stuff until it worked.</p> <p>Here is the working code <em>(this is the full contents of test-page.php)</em>:</p> <pre><code>&lt;?php $the_number = file_get_contents("count.txt"); ?&gt; PHP Number: &lt;?= $the_number ?&gt; &lt;script type="text/javascript"&gt; $a_variable_from_somewhere_that_is_a_number = 25; var another_number = $a_variable_from_somewhere_that_is_a_number var php_number = parseInt(&lt;?= $the_number ?&gt;); var javascript_number = parseInt(another_number); var combined_number = php_number + javascript_number; &lt;/script&gt; &lt;br /&gt;&lt;br /&gt; Did it work? &lt;script type="text/javascript"&gt;document.write(combined_number);&lt;/script&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload