javascript - PHP 使用 post 以编程方式导航到新表单

标签 javascript php forms post data-entry

我对 PHP 还很陌生。我有一个用户正在填写的表单,其中包含各种详细信息(开始日期、结束日期等),名为purchaseLicence.php。提交后,表单操作会重新加载自身以使用 PHP 验证数据。

如果验证通过,我希望它使用 post 方法导航到purchaseLicence2.php,就像表单最初直接发布到purchaseLicence2.php一样。

我不介意使用 Javascript 来完成此操作,并且我猜想它需要参与,因为它最终会看到一种与它原本期望的形式不同的形式。

这是我当前的purchaseLicence.php,我遇到的问题是purchaseLicence2.php和purchaseLicence.php都是在表单发布后呈现的,并且浏览器仍然指向purchaseLicence.php,而不是purchaseLicence2.php .

    <?php
        include_once('php/strings.php');
        include_once('php/sprocs.php');
        include_once('php/dates.php');

        $encounteredValidationError = false;
        $navigateAway=false ;

        if (isset($_POST['process']))
        {
            if ($_POST['process'] == 1)
            {
                // if here, form has been posted
                $ProductCode = $_POST['ProductCode'];
                $StartDate = $_POST['StartDate'];
                $EndDate = $_POST['EndDateHidden'];

                // standardise the date formats to ISO8601
                $StartDate = date("Y-m-d", strtotime($StartDate));
                $EndDate = date("Y-m-d", strtotime($EndDate));

                echo "<descriptive>" . PHP_EOL;
                echo "ProductCode:" . $ProductCode . "<br/>" . PHP_EOL;
                echo "StartDate:" . $StartDate . "<br/>" . PHP_EOL;
                echo "EndDate:" . $EndDate . "<br/>" . PHP_EOL;
                echo "</descriptive>" . PHP_EOL;


                // validation to happen here

                if (!$encounteredValidationError) 
                {
                    // so we're happy with the values. The form has just reloaded, so we need to put these back from $_POST into the input fields, so
                    // that we can call NavigateToPurchaseLicence2(), which will get them out of the input fields and post them to purchaseLicence2.php
                    // What a faff!

                    $data = array('ProductCode'=>$ProductCode, 'StartDate'=>$StartDate, 'EndDate'=>$EndDate);
                    $options = array(
                                    'http'=>array(
                                                    'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                                                    'method'  => 'POST',
                                                    'content' => http_build_query($data)
                                                )
                                    );

                    $context  = stream_context_create($options);
                    $result = file_get_contents('purchaseLicence2.php', false, $context);
                    if ($result === FALSE) { /* Handle error */ }

                    var_dump($result);
                }
                else
                {
                    // hilite errors in the form here, how? form is not yet loaded
                }
            }
        }
    ?>

</head>
<body>
    <form method="post" action="purchaseLicence.php" id="form1">
        <input type="hidden" name="process" value="1">
        <table border=0 width=800px align=left style="margin: 0px auto;">

            <tr> <!-- Product > -->
                <td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive>Product</descriptive></td>
                <td width="500px" bgcolor="lightgray">
                    <?php
                        // creates a dropdown of products
                        OutputSelectFromSQL("SELECT * FROM Product ORDER BY Description", "ProductCode", "ProductCode", "Description", "");
                    ?>
                </td>
            </tr>

            <tr> <!-- Licence Period -->
                <td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive>Licence Period</descriptive></td>
                <td width="500px" bgcolor="lightgray"><descriptive>1 year</descriptive></td>
            </tr>

            <tr> <!-- Start Date -->
                <td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive>Start/End Dates</descriptive></td>
                <td width="500px" bgcolor="lightgray">
                    <input type="date" style="font-family:verdana;font-size:12px;" name="StartDate" id="StartDate" onchange="updateEndDate(this.value);"></input>
                    <descriptive> to <a id="EndDate"></a></descriptive>
                    <input type="hidden" name="EndDateHidden" id="EndDateHidden"></input> <!-- this is used so we can post the end date to $_POST -->
                </td>
            </tr>

            <tr> <!-- Next > -->
                <td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive></descriptive></td>
                <td width="500px" bgcolor="lightgray" align="right"><input type="submit" value="Next"></input></td>
            </tr>

        </table>
    </form>
</body>

一个遵循标准模式的简单示例非常有用。

最佳答案

我建议您使用 $_SESSION 来保存表单之间的状态,下面是一个非常粗略的示例,第一个表单上有 1 个字段,如果良好(数字),则设置整个表单状态进入 session ,然后重定向到第二个表单以填写其他字段。非常简单,但您明白了。

dataentry1.php

<?php 
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // define form state
    $form = [
        'value' => $_POST,
        'error' => []
    ];

    // validate a_field
    if (empty($form['value']['a_field'])) {
        $form['error']['a_field'] = 'a_field is a required field!';
    } elseif (!is_numeric($form['value']['a_field'])) {
        $form['error']['a_field'] = 'a_field should be a number!';
    }

    // all good
    if (empty($form['error'])) {
        $_SESSION['form'] = $form;
        exit(header('Location: dataentry2.php'));
    }
}
?>

<?= (!empty($form['error']['global']) ? $form['error']['global'] : null) ?>

<form action="/dataentry1.php" method="post">
  <lable>a_field:</lable>
  <input type="text" name="a_field" value="<?= (isset($form['value']['a_field']) ? htmlentities($form['value']['a_field']) : null) ?>">
  <?= (!empty($form['error']['a_field']) ? '<br>'.$form['error']['a_field'] : null) ?>
  <br>
  <input type="submit" value="Submit">
</form> 

dataentry2.php - 需要填写之前的表格。

<?php 
session_start();

// set form into scope from session
if (!empty($_SESSION['form'])) {
    $form = $_SESSION['form'];
} else {
    $_SESSION['form']['error']['global'] = 'You must fill out dataentry1 form first';
    exit(header('Location: dataentry1.php'));
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // define form state
    $form = [
        'value' => array_merge($form['value'], $_POST),
        'error' => []
    ];

    // validate a_field
    if (empty($form['value']['b_field'])) {
        $form['error']['b_field'] = 'b_field is a required field!';
    } elseif (!is_numeric($form['value']['b_field'])) {
        $form['error']['b_field'] = 'b_field should be a number!';
    }

    // all good
    if (empty($form['error'])) {
        exit('Do something cool!');
    }
}
?>

<form action="/dataentry2.php" method="post">
  <lable>a_field:</lable>
  <input type="text" name="a_field" value="<?= (isset($form['value']['a_field']) ? htmlentities($form['value']['a_field']) : null) ?>" readonly="readonly">
  <?= (!empty($form['error']['a_field']) ? '<br>'.$form['error']['a_field'] : null) ?>

  <lable>b_field:</lable>
  <input type="text" name="b_field" value="<?= (isset($form['value']['b_field']) ? htmlentities($form['value']['b_field']) : null) ?>">
  <?= (!empty($form['error']['b_field']) ? '<br>'.$form['error']['b_field'] : null) ?>
  <br>
  <input type="submit" value="Submit">
</form> 

关于javascript - PHP 使用 post 以编程方式导航到新表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48278113/

相关文章:

javascript - Date.parse 意外返回字符串

javascript - JS使用charCodeAt()和fromCharCode获取Unicode字符(码值> 55349)

php - Laravel 5.3 对 sortBy 集合的分页

javascript - typescript 编译器 : @types/d3-tip - Cannot invoke an expression whose type lacks a call signature

javascript - JS 中非 CSS3 浏览器的 CSS3 图像旋转微调器?

php - 如何将 css 样式放入 php "echo' ed"html table td?

php - 如何从数据库中选择的前 10 个条目中更新前 5 个条目

php - 一张表格响应,添加多个表格行

jquery - 选择选项 : jQuery, 大小写并显示/隐藏表单字段

forms - 遍历 Sencha Touch 2 中的表单域