473,395 Members | 2,443 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Requesting data from php in javascript question

Hello I have been writing a game in javascript which works fine but I wanted to step it up and request the data of the game from the server. I haven't really used php...all I know is from the Internet and I couldn't really find the answer I was looking for. I asked around and they said this is really easy to implement but I still can't get it to work.

My problem is it doesn't work for some reason... I think I'm not calling the url of my php file correctly too. I have the code set in javascript already to take stings from my words and hints arrays but I want the data to be on the php file(server side). I hope that makes sense. Thanks for your replies BTW .

Basically, all I want is my words and hints to be requested from the arrays in the php code instead having the arrays on the client side. I hope it as simple as it sounds.

I have separate files for the javascript and the php:

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. # create PHP array:
  3. $words = array(,"Encyclopedia","Marsupial","Philadelphia");
  4. $hints    = array(array("Related to the Animal Kingdom","Scary to most people","Crawled up the water spout","Title of a movie","A fear","8 legs"),
  5.                  array("Has volumes","Endless knowledge","Sold door to door","Now online","Alphabetized","Literature"),
  6.                  array("Mammal","Think pouches","Australia","A group in the animal kingdom","Down under","Things that jump"),
  7.                  array("City in the US","Cheesesteak","Has a baseball team with the same first letter","New England","Pennsylvania","The City of Brotherly Love"));
  8.  
  9. if (isset($_GET['param'])){
  10.     //$words = $_GET['param'];
  11.     $return_value = $words[$i];
  12.         $return_value2 = $hints[$i];
  13.  
  14.     return $return_value;
  15.         return $return_value2;
  16. }
  17.  
  18. ?> 

This is the game code:

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  4. <head>
  5. <h1>The Word Smith</h1>
  6. </head>
  7. <body>
  8. <script language="javascript" type="text/javascript">
  9.  
  10. //preload the six images first
  11. var face0=new Image()
  12. face0.src="d1.gif"
  13. var face1=new Image()
  14. face1.src="d2.gif"
  15. var face2=new Image()
  16. face2.src="d3.gif"
  17. var face3=new Image()
  18. face3.src="d4.gif"
  19. var face4=new Image()
  20. face4.src="d5.gif"
  21. var face5=new Image()
  22. face5.src="d6.gif"
  23.  
  24. var url = "http://students.engr.scu.edu/~rnaderza/php/Lab8_Part1/WordSmith(Part2).php?param=";
  25.  
  26. words = document.getElementById("words").value;
  27. var hints = document.getElementById("hints").value;
  28. var randomdice, i=0;
  29. var playerOneScore=0;
  30. var playerTwoScore=0;
  31. var player=1;
  32. var hasRolled=false;
  33. var currentWordIndex;
  34.  
  35. function startAgain() {
  36.  guessed = " ";
  37.  document.game.hint.value = "";
  38.  hasRolled = false;
  39.  playerOneScore=0;
  40.  playerTwoScore=0;
  41.  currentWordIndex = Math.round((words.length - 1)*Math.random());
  42.  toGuess = words[currentWordIndex].toUpperCase();
  43.  document.game.currentPlayer.value = "Player 1, it is your turn!";
  44.  displayToGuess();
  45.  displayScores();
  46. }
  47.  
  48. function displayToGuess() {
  49.  pattern=""
  50.  for(i=0;i<toGuess.length;++i) {
  51.   if(guessed.indexOf(toGuess.charAt(i)) != -1)
  52.    pattern += (toGuess.charAt(i)+" ")
  53.   else pattern += "_ "
  54.  }
  55.  document.game.toGuess.value=pattern
  56. }
  57.  
  58. function badGuess(s) {
  59.  if(toGuess.indexOf(s) == -1) return true
  60.  return false
  61. }
  62. function winner() {
  63.  for(i=0;i<toGuess.length;++i) {
  64.   if(guessed.indexOf(toGuess.charAt(i)) == -1) return false
  65.  }
  66.  return true
  67. }
  68. function guess(s){
  69.  if(badGuess(s)){
  70.      if ( player == 1 )
  71.      {
  72.          player = 2;
  73.          hasRolled = false;
  74.          document.game.currentPlayer.value = "Player 2, it is your turn!";
  75.      }
  76.      else
  77.      {
  78.          player = 1;
  79.          hasRolled = false;
  80.          document.game.currentPlayer.value = "Player 1, it is your turn!";
  81.      }
  82.  }
  83.  else if(guessed.indexOf(s) == -1)
  84.  {
  85.      if ( player == 1 )
  86.          playerOneScore++
  87.      else
  88.          playerTwoScore++
  89.      guessed = s + guessed
  90.  }
  91.  
  92.  displayToGuess()
  93.  displayScores()
  94.  
  95.  if(winner()) {
  96.     currentPlayerWins()
  97.  }
  98. }
  99. function throwdice(){
  100.     if (hasRolled == false)
  101.     {
  102.         //create a random integer between 0 and 5
  103.         randomdice=(Math.round(Math.random()*5) + 1);
  104.         document.images["mydice"].src=eval("face"+randomdice+".src");
  105.         displayHint();
  106.     }
  107.     else
  108.         alert("Sorry, you have already rolled once this turn!!!");
  109.     hasRolled=true;
  110. }
  111.  
  112. function displayHint(){
  113.     document.game.hint.value = hints[currentWordIndex][randomdice]
  114. }
  115.  
  116. function displayScores(){
  117.     document.game.score1.value = playerOneScore;
  118.     document.game.score2.value = playerTwoScore;
  119. }
  120.  
  121. function guessword()
  122. {
  123. var name=prompt("Enter your guess:","");
  124. if (name!=null && name!="")
  125.   {
  126.       if ( toGuess == name )
  127.           currentPlayerWins()
  128.       else
  129.           currentPlayerLoses()
  130.   }
  131. else
  132. {
  133.     currentPlayerLoses()
  134. }
  135. }
  136.  
  137. function currentPlayerWins()
  138. {
  139.     gameWinner = "Player " +player +" has won the game!!!!";
  140.     alert(gameWinner)
  141.     startAgain()
  142. }
  143.  
  144. function currentPlayerLoses()
  145. {
  146.     if ( player == 1 )
  147.         gameWinner = 2;
  148.     else
  149.         gameWinner = 1;
  150.     gameWinner = "Player " +gameWinner +" has won the game!!!!";
  151.     alert(gameWinner)
  152.     startAgain()
  153. }
  154.  
  155. function giveUp()
  156. {
  157.     currentPlayerLoses()
  158.     startAgain()
  159. }
  160.  
  161. function buyvowel()
  162. {
  163.   if ( (player == 1 && playerOneScore > 0)
  164.           || (player == 2 && playerTwoScore > 0) )
  165.       {
  166.       var name=prompt("Enter a vowel:","");
  167.       if (name!=null && name!="")
  168.       {
  169.           guess(name.toUpperCase())
  170.           if ( player == 1 )
  171.               playerOneScore--;
  172.           else
  173.               playerTwoScore--;
  174.           displayScores();
  175.       }
  176.   }
  177.   else
  178.   {
  179.       alert("You do not have enough points to buy a vowel!!!");
  180.   }
  181. }
  182.  
  183. </script>
  184. <ul class="navbar">
  185.   <li><a href="gamerules.html">RULES</a></li>
  186. </ul>
  187. <form NAME="game">
  188.  
  189. Word to guess: <input type="text" name="toGuess" onfocus="stayAway()"><br><br>
  190. Hint: <input type="text" name="hint" size="90"><br><br>
  191. Player1_Score: <input type="text" size="10" id="score1" maxlength="20" /><br/>
  192. Player2_Score: <input type="text" size="10" id="score2" maxlength="20" /><br><br>
  193. <img src="d1.gif" name="mydice"><br><br>
  194.  
  195. <input type="text" name="currentPlayer" size="30">
  196. <input type="button" value="Throw dice!" onClick="throwdice()">
  197. <input type="button" value="Buy a vowel" onClick="buyvowel()">
  198. <input type="button" value="Guess word" onClick="guessword()"><br><br>
  199.  
  200.  
  201. <INPUT TYPE="BUTTON" VALUE=" B " ONCLICK="guess('B')">
  202. <INPUT TYPE="BUTTON" VALUE=" C " ONCLICK="guess('C')">
  203. <INPUT TYPE="BUTTON" VALUE=" D " ONCLICK="guess('D')">
  204. <INPUT TYPE="BUTTON" VALUE=" F " ONCLICK="guess('F')">
  205. <INPUT TYPE="BUTTON" VALUE=" G " ONCLICK="guess('G')">
  206. <INPUT TYPE="BUTTON" VALUE=" H " ONCLICK="guess('H')">
  207. <INPUT TYPE="BUTTON" VALUE=" J " ONCLICK="guess('J')">
  208. <INPUT TYPE="BUTTON" VALUE=" K " ONCLICK="guess('K')">
  209. <INPUT TYPE="BUTTON" VALUE=" L " ONCLICK="guess('L')">
  210. <INPUT TYPE="BUTTON" VALUE=" M " ONCLICK="guess('M')">
  211. <INPUT TYPE="BUTTON" VALUE=" N " ONCLICK="guess('N')">
  212. <INPUT TYPE="BUTTON" VALUE=" P " ONCLICK="guess('P')">
  213. <INPUT TYPE="BUTTON" VALUE=" Q " ONCLICK="guess('Q')">
  214. <INPUT TYPE="BUTTON" VALUE=" R " ONCLICK="guess('R')">
  215. <INPUT TYPE="BUTTON" VALUE=" S " ONCLICK="guess('S')">
  216. <INPUT TYPE="BUTTON" VALUE=" T " ONCLICK="guess('T')">
  217. <INPUT TYPE="BUTTON" VALUE=" V " ONCLICK="guess('V')">
  218. <INPUT TYPE="BUTTON" VALUE=" W " ONCLICK="guess('W')">
  219. <INPUT TYPE="BUTTON" VALUE=" X " ONCLICK="guess('X')">
  220. <INPUT TYPE="BUTTON" VALUE=" Y " ONCLICK="guess('Y')">
  221. <INPUT TYPE="BUTTON" VALUE=" Z " ONCLICK="guess('Z')"><BR><BR>
  222.  
  223. <INPUT TYPE="BUTTON" NAME="restart" VALUE="---- Start Again ----" ONCLICK="startAgain()">
  224.  <INPUT TYPE="BUTTON" NAME="giveup" VALUE="---- Give Up? ----" ONCLICK="giveUp()">
  225. <script language="JavaScript"><!--
  226. startAgain()
  227. // --></script>
  228.  
  229. </form>
  230. </body>
  231. </html>
Regards,
Van Dugall
Dec 9 '09 #1
1 2040
brixton
35
While it's still not that pretty to store the data in raw PHP format, I would in your case go for a simple Ajax call from the Javascript. So if you haven't read up on Ajax, do so, it's really neat.
Dec 9 '09 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Keith Bowes | last post by:
I have a script for requesting HTTP resources and I want it to use HTTP compression (to reduce bandwidth), if possible. What's the best way to do this? I've tried using zlib functions but they...
2
by: Pavils Jurjans | last post by:
Hello, I have a fairly complex project with server-side written in C# (.NET), and client-side heavily relying on the presence on JavaScript-compatible scripting engine. One of the features thie...
6
by: Jon Davis | last post by:
I recently learned how to do an <OBJECT> alternative to <IFRAME> in current browsers using: <object id="extendedhtml" type="text/html" data="otherpage.html" width="250" height="400"></object> ...
1
by: Charles A. Lackman | last post by:
Hello, I have made an aspx web application that is using Forms Authentication. Each unsecure page has a custom user control on it that will allow the visitor to login and enter secure pages. The...
2
by: Dnna | last post by:
I have a table which is bound to an Internet Explorer XML data island. I'm using ASP.NET's client-side validators for an input field in the table. The problem is that if the input fields are in...
12
by: Tom | last post by:
Hi everyone, I don't know if anyone can help me, I've got roughly 25 forms in a site, with between 10 and 70 fields on each form. Now, these fields need to be inserted into a DB, each form...
1
by: Aaron | last post by:
Not sure if this is the best spot to post this question, but I am not going to pay money to ask an installation question.... Anyways I am trying to install C# standard 2003 and it analyzes the...
232
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first...
3
by: timchilds | last post by:
I have the following request URL in an ASPx page: http://crm/custom/fileviewer/default.aspx?NAME I want to be able to parse the requesting URL and pass NAME into a variable. Can anyone give...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.