Home>
Question

By creating an API that returns html in PHP and clicking the confirmation button,
I was able to display the confirmation screen which is the response (html) from the API.

Described in api.php in the button element of the responded html
How can I get javascript to work?

I want to return to the original screen with the back button.
In the first place, it may be necessary to reconsider from the algorithm.

Source code
<body>
     Document 
    
      <p>Input screen</p>
      <form name = "myForm">
          <p>Q1.text:<input type = "text" name = "text1" value = "hoge" /></p>
          <p>Q2.radio:
              <input type = "radio" name = "radio1" value = "A" checked />A
              <input type = "radio" name = "radio1" value = "B" />B</p>
          <p>Q3.checkbox:
              <input type = "checkbox" name = "checkbox1 []" value = "A" />A
              <input type = "checkbox" name = "checkbox1 []" value = "B" checked />B
              <input type = "checkbox" name = "checkbox1 []" value = "C" checked />C</p>
          <input type = "button" value = "confirmation" />
      </form>
    
  <script>
        // Get work area
        const workArea = document.getElementById ("work");
        // When the confirmation button is pressed
        document.getElementById ("button"). addEventListener ("click", function () {
            const formElement = document.getElementById ('form');
            const formData = new FormData (formElement);
            formData.append ("name", "value");
            // Connect to api.php
            fetch ('./api.php', {
                method: "post",
                body: formData
            }). then ((res) =>{
                if (res.status! == 200) {
                    throw new Error ("error");
                }
                return res.text ();
            }). then ((text) =>{
                console.log (text);
                workArea.innerHTML = text;
            }) .catch ((error) =>{
                console.log (error.message);
            }). Finally (() =>{
                console.log ("finally");
            });
        });
  </script>
</body>


api.php

<? php
echo "<p>Confirmation screen</p>";
foreach ($_ POST as $key =>$value) {
    echo $key. ":<b>". $Value. "</B><br>";
}
echo'<input type = "button" value = "back">';
echo'<input type = "button" value = "registration">';
$text =<<<"EOT"
<script>
document.getElementById ("back"). addEventListener ("click", function () {
    console.log ("back");
});
</script>
EOT;
echo $text;
?>
  • Answer # 1

    You can set it on HTML with workArea.innerHTML and then addEvent.

Related articles