简体   繁体   中英

In PHP how do I send form data to a page but direct the user to another when he clicks the submit button?

Take this simple form as an example:

<form method="post" action="reports.php">
<input type="text" name="name">
<input type="text" name="email_address">
<input type="submit" value="Submit">

I want it to send the input fields data to the reports.php page but I want it to direct the user to the page uploads.php when he clicks the "Submit" button.

Using header("Location: uploads.php") on reports.php page is not an option because reports.php gathers the form data into a table for everyone to see. In the uploads.php page, the user will upload files that will also be visible on reports.php table.

How do I do this?

You can check if the method used in request to reports.php is POST , and redirect the user.

<?php
# reports.php

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    // process the data

    header("Location: ...");
    exit;
}

Or you can simply create a add_report.php file.

You could add "on form submit" event with javascript.

When the submit button is clicked - collect the form data with javascript and send it where is necessary. When the ajax worked - redirect the user to the desired page with javascript.

A complete example would be smth like:

for html

<form method="post" id="my_form">
<input type="text" name="name">
<input type="text" name="email_address">
<input type="submit" value="Submit">

for javascript

<script>
$(function(){
   $('#my_form').on('submit', function(e){
       e.preventDefault();
       var url = 'reports.php?' + $(this).serialize();
       $.get(url, function(){
           window.location.href = 'uploads.php';
       });
   })
})
</script>

more info can be found here: https://api.jquery.com/serialize/

You need to refactor your code.

It sounds like your use cases are:

  1. GET to uploads: Show uploads form
  2. POST to somewhere: Add to reports and then show uploads form
  3. GET to reports: Show reports list
  4. POST to reports: Add to reports and then show uploads form

Don't worry about making the "somewhere" be the reports file.

Separate out the "Add to reports" code into a function (or functions) and put them into a file of their own.

Then include that file in both reports and uploads.

Make the upload form submit to uploads and then call the "Add to reports" function.

Do something similar in reports.

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