2013-03-20 15 views
-1

我在php中有一個setcookie函數。 我有一個jQuery對話框,輸入字段和提交按鈕。當我在輸入字段中輸入郵政編碼並推送提交郵政編碼保存在一個php cookie中。在POST後設置cookie會給出「undefined index」的通知

該cookie將顯示在主頁上的輸入字段中。

現在是我的問題,當我沒有一個cookie集,所以例如我離開輸入字段空白,然後單擊提交它給我一個錯誤。但在輸入字段中。

我使用codeigniter,這可能是問題。

錯誤:

Message: Undefined index: name Filename: views/navmenu.php Line Number: 33

我的組cookie並形式的代碼:

<div id="dialog" class="hidden" title="Welkom bij OostWestRegioBest.nl"> 
Vul hier uw postcode in. 
<form method="post" action""> 
Postcode: <input type="text" name="name" size="25"> 
<input type="submit" value="Opslaan"> 
<input type="hidden" name="submitted" value="true"> 
</form> 

<?php 
// set the cookie with the submitted user data 
setcookie('name', $_POST['name']); 
?> 

<?php 
    if(isset($_POST['Submit'])) 
    { 
    header("location: {$_SERVER['PHP_SELF']}"); 
    } 
?> 

</div> 

我的輸入字段,cookie將在被顯示。

<input type="text" value='<?php echo $_COOKIE['name'] ?>'> 

希望有人能幫助我。

感謝。

+0

您訪問'$ _ POST [「名」]餅乾',即使沒有形成具有已經送走了。把'setcookie()'行放到下面的'if'塊中,你應該沒問題。 – 2013-03-20 08:19:57

+0

allright會試試:) – 2013-03-20 08:20:19

+0

爲了回答這個問題,我們不需要看到'views/navmenu.php'嗎? – halfer 2013-03-20 08:39:24

回答

1

請設置提交表單後,才

if(isset($_POST['Submit'])){ 
    setcookie('name', $_POST['name']); 
} 

可以改變輸入字段作爲

<input type="text" value='<?php echo isset($_COOKIE['name']) ? $_COOKIE['name'] : '' ?>'> 
+0

這是不對的。因爲if(isset($ _ POST ['Submit'])){if(isset($ _ POST ['name'])){ – 2013-03-20 08:29:33

+0

你的第二個代碼確實有效!感謝Vanga Sasidhar指導我。 – 2013-03-20 08:43:39

1

僅當$ _POST包含索引名稱的元素時才設置cookie。

你可以試試這個。

<?php 
    // set the cookie with the submitted user data 
    setcookie('name', isset($_POST['name']) ? $_POST['name'] : ""); 
?> 

或者僅當cookie包含索引名稱的元素時才設置cookie。

<?php 
    if (isset($_POST['name'])) { 
     // set the cookie with the submitted user data 
     setcookie('name', $_POST['name']); 
    } 
?> 

根據您的要求選擇任何一個。

+0

錯誤仍然顯示。它是codeigniter相關,所以我可以以某種方式隱藏這個錯誤?因爲當沒有設置cookie時,這只是一個問題。 – 2013-03-20 08:25:49

+0

嘗試第一個。它會在cookie中設置空值,並將在輸入中使用相同的值。 – 2013-03-20 08:29:25

+0

是的,但這是問題所在。當它是空的時候會給我錯誤。當它不是空的時候很好。 – 2013-03-20 08:30:10