简体   繁体   中英

Clicking button does nothing

I'm trying to make a program that takes 5 words from a database randomly and inserts them into an array. The page initially loads as desired, but nothing happens after the button is clicked. None of the alerts are ever triggered, so the function must never be entered, but why is beyond me. Also, I get an error saying name isn't a legitimate index (referencing line 13) the first time I try running it on a browser, so advice about that would be great too.

lingo.php:

<?php
    session_start();
    if (empty($_POST["name"])):
       $_SESSION["error"] = "You did not enter a name.";
       header("Location: entername.php");
    else:
       $name = $_POST["name"];
       setcookie("name", "$name", time()+3600);
    endif;
?>
<html>
  <head>
    <b>Welcome to Lingo, <?php echo $_COOKIE["name"]; ?></b><br />
    <script src = "http://code.jquery.com/jquery-latest.js"></script>
    <script type = "text/javascript" language = "javascript">
    var arr = [];
    function collectWords() {
        $.post("getWord.php",
    function(data) {
        arr[word1] = $(data).find("Word1").text();
        alert("function reached");
        alert(arr[word1]);
        arr[word2] = $(data).find("Word2").text();
        alert(arr[word2]);
        arr[word3] = $(data).find("Word3").text();
        alert(arr[word3]);
        arr[word4] = $(data).find("Word4").text();
        alert(arr[word4]);
        arr[word5] = $(data).find("Word5").text();
        alert(arr[word5]);
    });
    }
    </script>
  </head>
  <body>
    <table id = "theTable" border = "1" class = "thetable"> </table>
    <input type = "submit" value = "Start" onclick = "collectWords()">
  </body>
</html>

getWord.php

<?php
   $db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
   if ($db->connect_error):
      die ("Could not connect to db " . $db->connect_error);
   endif;

   $query = "select word from Words order by rand() limit 1";
   $result = $db->query($query);
   $rows = $result->num_rows;
   if ($rows >= 1):
      header('Content-type: text/xml');
      echo "<?xml version='1.0' encoding='utf-8'?>";
      echo "<Word1>";
      $row = $result->fetch_array();
      $ans = $row["word"];
      echo "<value>$ans</value>";
      echo "</Word1>";
   else:
      die ("DB Error");
   endif;

   $query = "select word from Words order by rand() limit 1";
   $result = $db->query($query);
   $rows = $result->num_rows;
   if ($rows >= 1):
      header('Content-type: text/xml');
      echo "<?xml version='1.0' encoding='utf-8'?>";
      echo "<Word2>";
      $row = $result->fetch_array();
      $ans = $row["word"];
      echo "<value>$ans</value>";
      echo "</Word2>";
   else:
      die ("DB Error");
   endif;

   $query = "select word from Words order by rand() limit 1";
   $result = $db->query($query);
   $rows = $result->num_rows;
   if ($rows >= 1):
      header('Content-type: text/xml');
      echo "<?xml version='1.0' encoding='utf-8'?>";
      echo "<Word3>";
      $row = $result->fetch_array();
      $ans = $row["word"];
      echo "<value>$ans</value>";
      echo "</Word3>";
   else:
      die ("DB Error");
   endif;

   $query = "select word from Words order by rand() limit 1";
   $result = $db->query($query);
   $rows = $result->num_rows;
   if ($rows >= 1):
      header('Content-type: text/xml');
      echo "<?xml version='1.0' encoding='utf-8'?>";
      echo "<Word4>";
      $row = $result->fetch_array();
      $ans = $row["word"];
      echo "<value>$ans</value>";
      echo "</Word4>";
   else:
      die ("DB Error");
   endif;

   $query = "select word from Words order by rand() limit 1";
   $result = $db->query($query);
   $rows = $result->num_rows;
   if ($rows >= 1):
      header('Content-type: text/xml');
      echo "<?xml version='1.0' encoding='utf-8'?>";
      echo "<Word5>";
      $row = $result->fetch_array();
      $ans = $row["word"];
      echo "<value>$ans</value>";
      echo "</Word5>";
   else:
      die ("DB Error");
   endif;
?>

You get the error on $_COOKIE["name"]; because said cookie isn't set until you set it. You don't set the cookie until someone has entered their names, so on the first load it will give an error.

http://www.thesitewizard.com/php/set-cookies.shtml "Note that you cannot set a cookie in PHP and hope to retrieve the cookie immediately in that same script session. Take the following non-working PHP code as an example:"

Found under the header: "How to get the contents of a cookie.

Fix this with a shorthand if statement, like so:

<b>Welcome to Lingo,
 <?php isset($_COOKIE["name"]) ? $_COOKIE["name"] : $_POST["name"]; //Checks if the cookie is set. If not, uses the $_POST name ?>! </b><br />

I have another question: Why are your words requested 1 at a time? Why not get all 5 words in 1 query? Also, why send them back as XML data? Since you seem to be handling the data yourself, I would personally recommend a simple loop on the PHP side, returning it as a handy pre-made JSON array. edit: Also important, PHP does not echo any content automatically. An AJAX call can only receive printed data. You need to echo your results at the end of your php script or you will return nothing

Like so:

   $query = "select word from Words order by rand() limit 5";
   $result = $db->query($query);
   $rows = $result->num_rows;
   $array = array();
   if ($rows >= 1):

$i = 0;//start the wordcount
//While there are results, loop. (Results are limited to 5, so it won't loop more than 5 times)
while($row = $result->fetch_row()){
  $i++;//Put this on top so it starts with "1"
  $array["word$i"] = $row[0]; //create the array
}
echo json_encode($array); //Turn array into json and echo it.
      else:
      die ("DB Error");
   endif;

Now, you will also need to change your Javascript side a tiny bit. This is how you will access the new array (created by php)

<script type = "text/javascript" language = "javascript">
function collectWords() {
    $.post("getWord.php",
function(data) {
alert(data); // show whether you get any data back in the first place. thanks @jDo
var arr = $.parseJSON(data);

    alert(arr.word1);
    alert(arr.word2);
    alert(arr.word3);
    alert(arr.word4);
    alert(arr.word5);
});
}
</script>

As you can see, this way saves you quite a lot of code and saves you a lot of word replacements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM