简体   繁体   中英

call php script from an html form

This is my first time posting a question... I've tried my best to search the archives and try to solve this to no avail... so this is not out of laziness but more out of inexperience/ignorance. Anyways, onto my question:

I have the following html part of a form:

    <form name="form1" method="post" action="script.php">
        <fieldset>
            <legend>Tell me your name</legend>

            First Name: <input type="text" name="name"><br>

            Submit:     <input type="submit" value="send">

        </fieldset>
    </form> 

And the file script.php contains the following:

<?php
   $name = "empty";
   if(!empty($_POST["name"]))
   {
     $name = $_POST["name"];
   }
   echo $name;
 ?>

Very simple/beginner stuff. When I submit the form, I am sent to a new page which prints either "empty" or anything I'd typed into the name form-field.

My question: How can I execute this script from any html page containing a form without having the browser redirect me to a new page which contains the script output? I want to run a script in the background/not leave the current page (not necessarily for printing a message, but maybe to store whatever I type into the form fields into a database for example). I've tried typing this into the 'action' part of the form (in the html file):

<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">

And it redirects me to another page and shows the error:

Not Found The requested URL /< was not found on this server. Apache/2.4.18 (Ubuntu) Server at localhost Port 80

Any help would be greatly appreciated. Thanks in advance.

Either combine the code into a single page:

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   $name = ....
   etc...
}
?>

<html>
<body>
... form ...
</body>
</html>

so that the code only triggers when the form is actually submitted (and not when the form is initially loaded).

Or you use AJAX to perform a background submission, leaving the original page intact and displayed to the user.

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