Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It's quite easy to pass data from PHP -> JS without resorting to hiding it inside the DOM. The trick is the json_encode() function - it will convert php strings, array, etc into a valid javascript format. See your example below, fixed up:</p> <pre><code>&lt;?php $world = file_get_contents('http://url.com/testworld.txt'); ?&gt; &lt;html&gt; &lt;head&gt; &lt;script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/game.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body onload="init()"&gt; &lt;script type="text/javascript"&gt; //World is defined here, and accessible to the javascript that runs on the page var world = &lt;?=json_encode($world)?&gt;; &lt;/script&gt; &lt;canvas id="game" width="650" height="366" style="border: 2px solid black;"&gt;&lt;/canvas&gt; &lt;br /&gt; &lt;h1&gt; Currently in development.&lt;/h1&gt; &lt;br /&gt; &lt;/body&gt; </code></pre> <p></p> <hr> <p>I'm pretty sure your troubles are occurring because of the way that scoping of variables works in javascript. This simple example <em>must</em> work for you:</p> <pre><code>&lt;?php $foo = "\"Hello world!\""; ?&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;script type="text/javascript"&gt; var foo = &lt;?=json_encode($foo)?&gt;; alert("The value of foo is: " + foo); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>So in the context of the inline script, the <code>foo</code> variable is present. Perhaps if your code were to look like:</p> <pre><code>&lt;script type="text/javascript"&gt; //Load the game world, and pass to the javascript lib var world = &lt;?=json_encode($world)?&gt;; loadWorld(world); &lt;/script&gt; </code></pre> <p>then you wouldn't have to worry about scoping so much?</p>
    singulars
    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.
 

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