简体   繁体   中英

How to stay on HTML form page and not navigate to php form action page

I am working on a html form which will connect to a database using a php script to add records.

I have it currently working however when I submit the form and the record is added , the page navigates to a blank php script whereas I would prefer if it when submitted , a message appears to notify the user the record is added but the page remains the same. My code is below if anyone could advise me how to make this change.

Html Form :

<html>
<form class="form" id="form1" action="test.php" method="POST">

<p>Name:
<input type="Name" name="Name" placeholder="Name">
</p>

<p>Age:
<input type="Number" name="Age" placeholder="Age">
</p>

<p>Address
<input type="text" name="Address" placeholder="Address">
</p>

<p>City
<input type="text" name="City" placeholder="City">
</p>

</form>

<button form="form1" type="submit">Create Profile</button>

</html>

PHP Database Connection Code :

<html>
<?php 
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array(  "UID" => "xxxxxxxxx",  "PWD" => "xxxxxxxx",  
"Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);

if( $conn === false )
 {
 echo "Could not connect.\n";
 die( print_r( sqlsrv_errors(), true));
 }

  $Name = $_POST['Name'];
  $Age = $_POST['Age'];
  $Address = $_POST['Address'];
  $City = $_POST['City'];

$query = "INSERT INTO [SalesLT].[Test]
    (Name,Age,Address,City) Values 
('$Name','$Age','$Address','$City');";

$params1 = array($Name,$Age,$Address,$City);                       
$result = sqlsrv_query($conn,$query,$params1);

sqlsrv_close($conn);
?>
</html>

Typically your action file would be something like thankyou.php where you'd put whatever message to the user and then maybe call back some data that was submitted over. Example:

Thank you, [NAME] for your oder of [ITEM]. We will ship this out to you very soon.

Or this file can be the the same page that your form resides on and you can still show a thank you message with some javascript if your page is HTML. Something like:

<form class="form" id="form1" action="test.php" method="POST onSubmit="alert('Thank you for your order.');" >

I am taking into consideration that your PHP Database Connection Code snipplet that you posted above is called test.php because you have both connecting to the data base and inserting data into the database in one file.

Taking that into consideration, I think the only line you are missing, to return you back to to top snipplet of code that I shall call index.php would be an include statement just after the data has been added to the database

$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values ('$Name','$Age','$Address','$City');";

$params1 = array($Name,$Age,$Address,$City);                       
$result = sqlsrv_query($conn,$query,$params1);
echo "Data added";
include 'index.php'; //This file is whatever had the earlier form

Once you hit the submit button on your form, test.php is called, your data is handled and passed back to index.php.

NB: The other thing i should mention is to make it a habit of using mysqli_real_escape_string() method to clean the data that is in the $_POST[]; because in a real website, if you don't, you give an attacker the chance to carry out SQL injection on your website :)

you said page is coming blank and data is saved so i assumed that there are two files one which contains form and another which contains php code (test.php). when you submit the form you noticed that form is submitted on test.php and your test.php has no any output code that's why you are seeing blank page. so make a page thankyou.php and redirect on it when data is saved. header('Location: thankyou.php'); at the end of file.

Put this in form action instead of test.php

 <form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">

    Put your php code at top of the page. 

    $Name = $_POST['Name'];
    This is step closer to being a safer way to posting into your db as well.
    $Name =mysqli_real_escape_string( $_POST['Name']);

I like the jscript Alert from svsdnb to tell user data was successfully added to db.

This is not intended to be an out of the box solution; it's just to get you pointed in the right direction. This is completely untested and off the top of my head.

Although you certainly could do a redirect back to the html form after the php page does the database insert, you would see a redraw of the page and the form values would be cleared.

The standard way to do what you're asking uses AJAX to submit the data behind the scenes, and then use the server's reply to add a message to the HTML DOM.

Using JQuery to handle the javascript stuff, the solution would look something like this:

HTML form

<html>
  <!-- placeholder for success or failure message -->
  <div id="ajax-message"></div>

  <form class="form" id="form1">
    <p>Name: <input type="Name" name="Name" placeholder="Name"></p>
    <p>Age: <input type="Number" name="Age" placeholder="Age"></p>
    <p>Address: <input type="text" name="Address" placeholder="Address"></p>
    <p>City: <input type="text" name="City" placeholder="City"></p>

    <!-- change button type from submit to button so that form does not submit.  -->
    <button id="create-button" type="button">Create Profile</button>

  </form>

  <!-- include jquery -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <!-- ajax stuff -->
  <script>
    // wait until DOM loaded
    $(document).ready(function() {

      // monitor button's onclick event
      $('#create-button').on('click',function() {

        // submit form
        $.ajax({
          url: "test.php",
          data: $('#form1').serialize,
          success: function(response) {
            $('#ajax-message').html(response);
          }
        });
      });
    });
  </script>
</html>

test.php

<?php
// note:  never output anything above the <?php tag.  you may want to set headers.
// especially in this case, it would be better to output as JSON, but I'm showing you the lazy way.
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx", "Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);

if( $conn === false ) {
 echo "Could not connect.\n";
 die( print_r( sqlsrv_errors(), true));
}

$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];

// if mssql needs the non-standard brackets, then put them back in...
// note placeholders to get benefit of prepared statements.
$query = "INSERT INTO SalesLT.Test " .
         "(Name,Age,Address,City) Values " .
         "(?,?,?,?)";
$params1 = array($Name,$Age,$Address,$City);

$success = false;
if($result = sqlsrv_query($conn,$query,$params1)) {
  $success = true;
}

sqlsrv_close($conn);

// normally would use json, but html is sufficient here
// done with php logic; now output html

if($success): ?>
  <div>Form submitted!</div>
<?php else: ?>
  <div>Error: form not submitted</div>
<?php endif; ?>

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