To do this, you just need to output the script to a PHP page containing your data, and then you can access it from any other Javascript on the page, including jQuery and .ajax ().
Again, if you just want to pass it through an AJAX call, just use json_encode ():
<?php echo json_encode( array( 'groupidlist'=>$groupids, 'groupnamelist'=>$groupnames, 'serverurl'=>$serverurl, 'uid'=>$curuser->getID() ) ); ?>
And then handle it with callback functions from .ajax() or, perhaps better, .getJSON() , which is built for this purpose only.
I promise that it's not just spamming my blog here, but I wrote a message about passing variables between Javascript and PHP , because I did it often enough to come up with a simple / reliable / clean and reusable way to do this. If you regularly transfer data from PHP to Javascript and do not need AJAX, I will insert the basic information here:
At the top of each external js file, I add comments regarding what PHP variables are needed, so I can keep track of what I need when I turn it on (this is optional, of course, but nice):
Then in the PHP file, I pass the necessary variables with a single line of Javascript, assigning a JSON array with all the necessary values. Examples in PHP directly from my code:
<script type="text/javascript"> var phpvars = <?php echo json_encode( array( 'groupidlist'=>$groupids, 'groupnamelist'=>$groupnames, 'serverurl'=>$serverurl, 'uid'=>$curuser->getID() ) ); ?>; </script>
Once this is set up, I can simply access any PHP variables that I need in Javascript through the phpvars array. For example, if I need to set the image source using my serverurl, I could do the following:
imgElement.src = phpvars.serverurl + '/images/example.png';
Since it uses JSON, there is no need to worry about not wrapping anything in your Javascript while trying to insert PHP variables. Encoding / decoding of variables is processed at both ends by the built-in JSON functions, so it is very difficult to break them and send the variables brainlessly - you pass them in the same way as any other PHP array. In my game, which led to this, I had problems with both of them, and this solution will take care of them beautifully.