Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can do two things:</p> <ol> <li>Approach the problem properly.</li> <li>Half-ass it.</li> </ol> <p>I will give the second instruction first because it should give you some undestanding of how these two technologies are related.</p> <h1>Half ass it</h1> <p>This assumes that the script you are writing is not Ajax-based - just some standard generate-page-with-PHP and include .js.</p> <ol> <li><p>Write a php file that will generate Javascript content: </p> <pre><code>// /js/vars.php $v1 = $v2 = $v3 = $v4 = time(); header("Content-type: text/javascript"); echo "window.Variables = { v1: $v1, v2: $v2, v3: $v3, v4: $v4 }"; </code></pre> <p>(note that if the variables are strings, you should add quotes)</p></li> <li><p>Require that file in <code>&lt;head&gt;</code> before the file you want to use the variables in.</p> <pre><code>&lt;script type="text/javascript src="/js/vars.php"&gt; </code></pre></li> <li><p>Use it in your .js file.</p> <pre><code>var smth = Variables.v1 + Variables.v2; </code></pre></li> </ol> <p>How this is a no-no for many reasons, amongst them:</p> <ul> <li>JavaScript generated by a PHP file is not easily maintainable.</li> <li>The global JS namespace is somewhat messy.</li> <li>It does not play well with Ajax.</li> </ul> <h1>Proper</h1> <ol> <li><p>Write a php file that will generate JSON data:</p> <pre><code>// /js/vars.php $v1 = $v2 = $v3 = $v4 = time(); $jsonArr = array( 'v1'=&gt; $v1, 'v2'=&gt; $v2, 'v3'=&gt; $v3, 'v4'=&gt; $v4 ); header("Content-type: application/json"); echo json_encode($jsonArr); </code></pre></li> <li><p>Write some JavaScript code that will pull the data using Ajax. Eg. using jQuery:</p> <pre><code>$.getJSON('js/vars.php', function(data) { alert(data.v1+data.v2); }); </code></pre></li> </ol>
    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.
    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