Jump to content
  • Advertisement
Sign in to follow this  
RLS0812

Sharing Variables With JavaScript & PHP

This topic is 1857 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

 I'm in the middle of developing a JavaScript game using the canvas features, have ran into issues related to I/O .

 In JavaScript I have no file handling capabilities, no way to create, modify, or access data bases, and no real objects .

 

 I was wondering what the easiest way of passing variables back and forth between PHP & JavaScript / JavaScript & PHP .

 

 I have seen a couple examples doing a Google search, but no good explanation on how it's done.

 From what I can tell the way it's done it to output PHP code in the JavaScript ""document.write('PHP code here');"" , and output JavaScript code in the PHP ""echo 'JavaScript code here' ;"" .

 

 How does this work, and is there an easier way this can be done ? ( without AJAX )

 

 Thank you for your time.

Share this post


Link to post
Share on other sites
Advertisement

Your PHP code is running on the webserver whenever a user requests a page. Your Javascript code is running in the client's browser.

If you use document.write('PHP code here');, then all that will happen is that PHP code will appear on the clients screen.

In order to actually execute some PHP code on the server, the javascript code has to make a request to the webserver. You can either do this by loading a whole new page (as if the user clicked a link), or by using AJAX etc to load a new page in the background and extract information from it.

 

For the other direction, yes, the PHP code is typically outputting a HTML document, so you can echo a < script> tag with JS code in it, which will be executed by the client's browser when it loads the document.

Edited by Hodgman

Share this post


Link to post
Share on other sites

Aside from doing AJAX calls, you could use HTML5 Web Storage to store data. Have you looked into that? If you are trying to keep track of things like scores for top scores amongst all players around the world then yes you would want to probably use AJAX to send data to a PHP script (runs in the background as stated above).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!