2017-03-17 103 views
0

我正在製作日曆網絡應用程序,當我點擊某個表單時彈出一個表單。如果我使用$_SERVER["REQUEST_METHOD"] == "POST"isset($_POST['submit'])來檢查表單是否已提交,即使在刷新頁面並且未點擊提交時,echo代碼仍會執行。我如何確保只有在我提交表單時才能檢索表單數據?檢查表單是否已提交

<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"> 
        Event Title:<br> 
        <input type="text" name="eventTitle" id="eventTitle" maxlength="15" size="20" placeholder="Code.fun.do" required><br><br> 
        Event Description:<br> 
        <textarea name="eventDescription" rows="5" cols="50"></textarea><br><br> 
        From:<br> 
        <input type="time" name="eventTimeFrom"><br><br> 
        To:<br> 
        <input type="time" name="eventTimeTo"><br><br> 
        <input id="eventSave" type="submit" name="submit" value="Save"> 
</form> 

<?php 
      $eventTitle = $eventDescription = $eventTimeFrom = $eventTimeTo = ""; 
      //if ($_SERVER["REQUEST_METHOD"] == "POST") { 
      if(isset($_POST['submit'])) { 
       echo "<h2>something</h2>"; 
       $eventTitle = test_input($_POST["eventTitle"]); 
       $eventDescription = test_input($_POST["eventDescription"]); 
       $eventTimeFrom = test_input($_POST["eventTimeFrom"]); 
       $eventTimeTo = test_input($_POST["eventTimeTo"]); 
      } 
      function test_input($data) { 
       $data = trim($data); 
       $data = stripslashes($data); 
       $data = htmlspecialchars($data); 
       return $data; 
      } 
?> 
+0

你想保存提交後的值? –

+0

@MasivuyeCokile我正在使用JavaScript獲取表單數據並將其顯示在日曆中。 –

+0

你的問題標題說了別的,你的身體還有別的東西,你能解釋清楚你想要什麼嗎? –

回答

1

當您提交表單。 POST請求被髮送到服務器。

您可以通過重定向頁面,一旦你完成了你的腳本與此所做的工作避免這種情況:

header("Location: http://mypage.php"); 
die(); 

現在,這裏的問題是,你失去呼應數據的數據,所以你可以添加東西給一個成功消息:現在

header("Location: http://mypage.php?success=true"); 
die(); 

,在你的腳本,你可以有這樣的地方輸出會去:

<?php 
if (isset($_GET['success'] && $_GET['success'] == 'true')) { 
    echo 'Your form has been submitted!'; 
} 

這應該避免你遇到的麻煩。還有其他技巧,你應該使用一個適合你的技術。

在附註中,當您在瀏覽器中使用向前和向後按鈕時,POST請求也會重新提交 - 您也應該注意這一點。

+1

其他技術包括使用會話和/或唯一的網址 - 但我不想在這個特定的答案中進入。 –