简体   繁体   中英

How can I submit form and stay on the same page after require?

I have a code which its simplified version could look like this:

file1.php

$array = array();
$array = new randomObject(1);
$array = new randomObject(2);
require('file2.php');

file2.php

<form  method="post" action="?">
 <?php
        foreach ($array as $a) {                           
             <p><?php echo $a->getAValue();  
                <textarea rows="5" cols="70" name="textbox[]"> 
                </textarea>
             </p>
  <?php } ?>
        <input id="isTrue"> //true or false
        <input type="submit" >
</form>

The user is supposed to write answers in the textarea and click on submit then his answers are compared to the randomObject values. Then it shows if it's true or false next to each textarea

You are looking for something that the fron-tend will handle for you and an AJAX call is exactly what you need.

First of all, name your form

<form id="myForm"  method="post" action="?">
 <?php
        foreach ($array as $a) {                           
             <p><?php echo $a->getAValue();  
                <textarea rows="5" cols="70" name="textbox[]"> 
                </textarea>
             </p>
  <?php } ?>
        <input id="isTrue"> //true or false
        <input id="submitButton" type="submit" >
</form>

Now you have proper id's both on the submit button and on the form itself.

<script>
let submitB = document.querySelector("#submitButton");
submit.addEventListener("click", function(e) {
    e.preventDefault();
});
</script>

From now on you just have to write a proper ajax call to the url you wanted to access and you will be set to go.

If you need help with that let me know and I will throw something your way.

I am guessing you want to retain the values entered by the user, since they go away if you submit the form. (Page reloads) This can be done by altering the input fields. If a value was submited pass that value to each corresponding input field.

Something like that:

<textarea rows="5" cols="70" name="textbox[]" <?php if(isset(value[SOMETHING])){?> value="<?php echo value[SOMETHING]; ?>" <?php } ?> >

This is just an example of how it would work. Make sure you adapt it to your code!

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