简体   繁体   中英

Change inner HTML based on PHP return

I have a simple web page with a form consisting of a text entry box and a button. The onclick event of the button fires a script in the head. The script calls a separate PHP page, and checks the submitted text. If the value is "foo" it should say correct, if it's anything else it should say incorrect.

No matter how I tweak it, I can't get anything to show up in the inner HTML of the div with the id of response_one. I'm working off of the W3Schools tutorial found here but just can't seem to make this work. I've included the html / PHP below, any pointers would be greatly appreciated.

The HTML:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>See</title>
    <script>
    function show(str) {
      if (str.length == 0) {
        document.getElementById("response_one").innerHTML = "";
        return;
      } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            document.getElementById("response_one").innerHTML = this.responseText;
          }
        };
        xmlhttp.open("GET", "check_one.php?q=" + str, true);
        xmlhttp.send();
      }
    }
    </script>
  </head>
  <body>
    <div id="mainbody">
  <form>
    Answer: <input type="text" name="answers">
    <input type="submit" onclick="show(this.value)">
  </form>
  <div id="response_one"></div>
</div>
  </body>
</html>

and check_one.php:

<?php
$q = $_REQUEST["q"];
$q = strtolower($q)

$result = ""

if ($q === "foo") {
  $result = "Correct";
} else {
  $result = "Incorrect";
}

echo $result
 ?>

It seems you have forgot some of the ";" at the end of the code. How about

<?php
$q = $_REQUEST["q"];
$q = strtolower($q)

$result = ""

if ($q === "foo") {
  $result = "Correct";
} else {
  $result = "Incorrect";
}

echo $result
 ?>

To

<?php
$q = $_REQUEST["q"];
$q = strtolower($q);

$result = "";

if ($q === "foo") {
  $result = "Correct";
} else {
  $result = "Incorrect";
}

echo $result;
 ?>

Problems

Multiple problems here:

  1. Your button is a submit input. On click, your browser will submit the form. None of your AJAX would matter because the page will refresh before you see any result.
  2. Your button does not hold the value. The input field <input type="text" name="answers"> does. It is a mistake to run show(this.value) because you don't really plan to check the submit button's value.
  3. There are multiple syntax error in your check_one.php file. Please run command line php -l check_one.php or use browser to browse check_one.php?q=foo to check it.

Quick Fix

I'll leave the php syntax error to you and focus on your form. Here is how I'm going to fix it:

  1. Change the submit button from <input type="submit"> to <button type="button"> . This will prevent form submission on click.
  2. Alter the onClick function to access the value of your text input answers instead of this.value .

The Code

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>See</title>
    <script>
      function show(str) {
        if (str.length == 0) {
          document.getElementById("response_one").innerHTML = "";
          return;
        } else {
          var xmlhttp = new XMLHttpRequest();
          xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
              document.getElementById("response_one").innerHTML = this.responseText;
            }
          };
          xmlhttp.open("GET", "check_one.php?q=" + str, true);
          xmlhttp.send();
        }
      }
    </script>
  </head>
  <body>
    <div id="mainbody">
      <form>
        Answer:
        <input type="text" name="answers">
        <button type="button" onClick="show(this.form['answers'].value)">Check</button><!-- only this line is changed -->
      </form>
      <div id="response_one"></div>
    </div>
  </body>
</html>

Once you fixed your check_one.php , you'll get your desired result.

Room for Improvement

There can still be problem with your form. If the user press "Enter" instead of clicking the button, your form will be submitted. So instead of just intercepting the click event of the button, you'd be better off capturing the form's submit event .

So here are the improvements:

  1. Add an id attribute to your form.
  2. Use document.getElementById to find the form and intercept the submit event .
  3. Use event.preventDefault() to prevent form submission.
  4. Find the answers value and do the XMLHttpRequest .

The Code

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>See</title>
  </head>
  <body>
    <div id="mainbody">
      <form id="check-form"><!-- added id="check-form" -->
        Answer: <input type="text" name="answers">
        <input type="submit"><!-- removed onClick attribute -->
      </form>
      <div id="response_one"></div>
    </div>
  </body>
  <script>
    // Moved script after body so the form element would exist before
    // this script is run.
    document.getElementById('check-form').addEventListener('submit', function (evt) {
      evt.preventDefault(); // prevent form submission
      var str = evt.target["answers"].value; // get the answers field value

      // The logics previously in your `show()` function
      if (str.length == 0) {
        document.getElementById("response_one").innerHTML = "";
        return;
      } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            document.getElementById("response_one").innerHTML = this.responseText;
          }
        };
        xmlhttp.open("GET", "check_one.php?q=" + str, true);
        xmlhttp.send();
      }
    });
  </script>
</html>

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