2016-06-07 318 views
13

當我嘗試檢查用戶輸入名稱是否已經存在時,通過ajax表單提交!但它只在sessions.php中得到Undefined index: username,缺什麼?

<form action="" method="POST" id="saveuser" enctype="multipart/form-data"> 
<input type="text" name="username"><br> 
<input type="password" name="pass"><br> 
<input type="file" name="fileupload"><br> 
<input type="submit" name="submit" value="Confirm" id="confirm"> 
</form> 
<script type="text/javascript"> 
    $('#confirm').click(function(e){ 
     e.preventDefault(); 
     $.ajax({ 
      type:'POST', 
      url :"sessions.php", 
      data:$("#saveuser").serialize(), 
      contentType : false, 
      processData: false,    
      success: function(d){ 
       console.log(d);//[error] :Undefined index: username 
      } 
     }); 
    }); 
</script> 

sessions.php

<?php 
$exist = "david"; 
if($_POST['username'] == $exist){ 
    echo json_encode("Already exist"); 
} 
else{ 
    echo json_encode("You can succesfully add"); 
} 
?> 
+3

寫的print_r($ _ POST);在session.php中,你找到該數組中的用戶名? –

+0

是你在同一頁中的表格 –

+0

我有空陣列,但在網絡選項卡上,我可以看到我的參數! @Kaushalshah –

回答

7

有你的代碼一些問題,如:

  • ...它只是得到了一個未定義的索引:在sessions.php用戶名

    問題是因爲以下兩行

    contentType : false, 
    processData: false, 
    

    F ROM the documentation

    的contentType(默認值:'application/x-www-form-urlencoded; charset=UTF-8'
    類型:BooleanString
    當發送數據到服務器時,使用該內容類型。默認是「application/x-www-form-urlencoded; charset = UTF-8」,這對大多數情況來說都很好。如果明確地將內容類型傳遞到$.ajax(),那麼它總是被髮送到服務器(即使沒有數據發送)。從jQuery 1.6開始,你可以通過false告訴jQuery不設置任何內容類型頭。

    過程數據(默認:true
    類型:Boolean
    默認情況下,該數據選項傳遞作爲一個對象的數據(從技術上講,任何其他不是字符串)將被處理並轉換成一個查詢字符串,以適應默認的內容類型的「application/x-www-form-urlencoded」。如果要發送DOMDocument或其他未處理的數據,請將此選項設置爲false

    因此,$_POST陣列將在sessions.php頁是空的,如果你設置contentTypeprocessDatafalse,這就是爲什麼你得到這個未定義指數:用戶名錯誤。但是話雖如此,由於您使用AJAX請求發送文件,因此可以將這些設置設置爲false,這將在以下幾點中進一步說明。

  • .serialize()方法創建通過串行化形式的控制值,如<input><textarea><select>一個URL編碼文本字符串。但是,它在序列化表單時不包含文件輸入字段,因此您的遠程AJAX處理程序根本不會收到該文件。因此,如果您通過AJAX上傳文件,請使用FormData對象。但請記住,舊的瀏覽器不支持FormData對象。 FormData支持從以下桌面瀏覽器版本開始:IE 10+,Firefox 4.0+,Chrome 7+,Safari 5+,Opera 12+。

  • 由於您期望從服務器獲取json對象,因此請將此設置dataType:'json'添加到您的AJAX請求中。 dataType是您期待從服務器返回的數據類型。

因此,解決辦法是這樣的:

讓您HTML形式,因爲它是,改變你的的jQuery/AJAX腳本按以下方式,

$('#confirm').click(function(e){ 
    e.preventDefault(); 

    var formData = new FormData($('form')[0]); 
    $.ajax({ 
     type: 'POST', 
     url : 'sessions.php', 
     data: formData, 
     dataType: 'json', 
     contentType: false, 
     processData: false,    
     success: function(d){ 
      console.log(d.message); 
     } 
    }); 
}); 

並在sessions.php頁面上處理您的表單,如下所示:

<?php 

    $exist = "david"; 
    if(isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['pass']) && !empty($_POST['pass'])){ 
     if($_POST['username'] == $exist){ 
      echo json_encode(array("message" => "Already exist")); 
     }else{ 
      echo json_encode(array("message" => "You can succesfully add")); 

      // get username and password 
      $username = $_POST['username']; 
      $password = $_POST['pass']; 

      // process file input 
      // Check whether user has uploaded any file or not 
      if(is_uploaded_file($_FILES['fileupload']['tmp_name'])){ 

       // user has uploaded a file 

      }else{ 
       // no file has been uploaded 
      } 
     } 
    }else{ 
     echo json_encode(array("message" => "Invalid form inputs")); 
    } 

?> 
-5

刪除方法,動作:從你的表單標籤後,空白,因爲你需要給只AJAX方法的所有細節。

這將解決AJAX希望

<form id="saveuser" enctype="multipart/form-data"> 
+2

如果' method =「post」'被移除,那麼他將如何獲得'$ _POST'變量值? – Apb

+0

你正在做這個由ajax,如果你正在做它與ajax你不需要形式標籤本身實際上只有ajax可以做的事情..發佈變量和數據..試試這個.. – LaviJ

+0

@ Apb你不需要把使用ajax方法提交表單時,在表單標記中使用方法和動作屬性。 – vartika

0

更改你的腳本

<script type="text/javascript"> 
$(function(){ 
    $('#confirm').click(function(e){ 
     e.preventDefault(); 
     $.ajax({ 
      type:'POST', 
      url :"sessions.php", 
      data:$("#saveuser").serialize(), 
      contentType : false, 
      processData: false,    
      success: function(d){ 
       console.log(d);//[error] :Undefined index: username 
      } 
     }); 
    }); 
}); 
</script> 
3

使用.post的$():

$('#confirm').click(function(e){ 

    e.preventDefault(); 

    $.post("sessions.php", $.param($("#saveuser").serializeArray()), function(data) { // use this ajax code 
     console.log(data); 
    }); 

}); 
4

你設置的contentType爲假,即爲什麼PHP不能解析你的帖子主體

3

使用下面的代碼在你的HTML代碼,並刪除的contentType:假的, 過程數據:假

<form action="" method="POST" id="saveuser" enctype="multipart/form-data"> 
    <input type="text" name="username"><br> 
    <input type="password" name="pass"><br> 
    <input type="file" name="fileupload"><br> 
    <input type="submit" name="submit" value="Confirm" id="confirm"> 
</form> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script> 
<script type="text/javascript"> 
    $('#confirm').click(function(e){ 
     e.preventDefault(); 
     $.ajax({ 
      type:'POST', 
      url :"sessions.php", 
      data: $('#saveuser').serialize(), 
      success: function(d){ 
       console.log(d);//[error] :Undefined index: username 
      } 
     }); 
    }); 
</script> 
1

你需要改變你的腳本:

嘗試使用的new FormData代替.serialize()

<script type="text/javascript"> 
    $('#confirm').click(function(e){ 
     e.preventDefault(); 
     var formData = new FormData($("#saveuser")[0]); 
     $.ajax({ 
      type:'POST', 
      url :"tt.php", 
      data:formData, 
      contentType : false, 
      processData: false,    
      success: function(d){ 
       console.log(d);//[error] :Undefined index: username 
      } 
     }); 
    }); 
</script> 

注:您使用contentTypefalse意味着jQuery的不添加Content-Type頭。您正在使用jQuery的.serialize()方法,它使用標準的URL編碼表示法創建一個文本字符串。使用「contentType:false」時,您需要傳遞未編碼的數據。

12

如果你設置的contentType ,阿賈克斯頭不發送,在結果如果您發送somehing type:POST頭不包含你的數據,因此服務器無法看到它。如果您使用GET來執行此操作,它將會正常工作,因爲數據在GET(url之後)不在標頭中。

只是刪除的contentType

$.ajax({ 
      type:'POST', 
      url :"sessions.php", 
      data: $("#saveuser").serialize(), 
      success: function(d){ 
       console.log(d); 
      } 
    }); 

的contentType

(缺省: '應用/ X WWW的窗體-urlencoded; 字符集= UTF-8')

類型:布爾值或字符串將數據發送到 服務器時,請使用此內容類型。默認爲 「application/x-www-form-urlencoded; charset = UTF-8」,這對於大多數情況是適用的 。如果您明確地將內容類型傳遞給$。ajax(),然後 它總是發送到服務器(即使沒有數據發送)。截至 jQuery 1.6你可以通過false告訴jQuery沒有設置任何內容 類型的頭。注意:W3C XMLHttpRequest規範規定,字符集始終是UTF-8;指定另一個字符集不會強制 瀏覽器更改編碼。注意:對於跨域請求,將內容類型設置爲 應用程序/ x-www-form-urlencoded,multipart/form-data或text/plain 將會觸發瀏覽器發送預檢OPTIONS請求到 服務器。

過程數據被用於發送數據,因爲它是 - Ajax documentation

將數據發送到服務器

默認情況下,Ajax請求使用HTTP GET方法發送。如果需要 POST方法,則可以通過爲類型選項設置 值來指定方法。此選項影響數據選項 的內容如何發送到服務器。根據W3C XMLHTTPRequest標準,POST數據將始終使用UTF-8字符集傳輸到服務器的 。

數據選項可以包含形式 KEY1的查詢字符串=值1 &鍵2 =值,或形式{鍵: 'VALUE1', KEY2: '值'}的對象。如果使用後一種形式,則在發送數據之前使用jQuery.param()將數據轉換爲查詢字符串 。處理可以通過將processData設置爲false來繞開。如果您希望將XML對象發送到服務器 ,則 處理可能不受歡迎;在這種情況下,請將contentType選項從 application/x-www-form-urlencoded更改爲更合適的MIME類型。

3

考慮到這是你的HTML表單


 
    <form method="POST" id="saveuser" enctype="multipart/form-data"> 
 
     <input type="text" name="username" id="username"><br> 
 
     <input type="password" name="pass" id="pass"><br> 
 
     <input type="file" name="fileupload"><br> 
 
     <input type="submit" name="submit" value="Confirm" id="confirm"> 
 
    </form>

可以調用jQuery函數這樣

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script> 
 
    jQuery("#saveuser").submit(function() { 
 
    
 
    \t \t //Validate the input here 
 
    
 
    \t \t jQuery.ajax({ 
 
    \t \t \t type: 'POST', 
 
    \t \t \t url: 'sessions.php', 
 
    \t \t \t data: jQuery('#saveuser').serialize(), 
 
    
 
    \t \t \t success: function (msg) { 
 
    \t \t \t \t msg = jQuery.trim(msg); 
 
    \t \t \t \t if (msg == 'Success') { 
 
         //Do Whatever \t \t \t \t \t 
 
         //jQuery("#thanks_message").show('slow'); 
 
    \t \t \t \t } 
 
    \t \t \t } 
 
    \t \t }); 
 
    \t \t return false; 
 
    \t });

你會在你的會話中得到所有的參數。php文件像

<?php 

    $username = trim($_POST['username']); 
    $pass = trim($_POST['pass']); 
    //rest of the params of the form 

    $exist = "david"; 
    if ($username == $exist) { 
    echo json_encode("Already exist"); 
    } else { 
    echo json_encode("You can succesfully add"); 
    } 
?> 

我希望這可以解決您的問題。

+0

我試過了。 無法運行PHP代碼段代碼,但它適用於我。 –

+0

不幸的是,由於JS發送後params到一個PHP頁面,這就是爲什麼它不能在小提琴中工作。我希望SO很快就會實現PHP小提琴。 –

2
<form method="POST" id="saveuser" enctype="multipart/form-data"> 
<input type="text" name="username"/><br> 
<input type="password" name="pass"/><br> 
<input type="file" name="fileupload"/><br> 
<input type="button" name="save" id="save" value="save"/> 
</form> 

<script type="text/javascript"> 
    $('#save').click(function(e){ 
     var form = new FormData(document.getElementById('#saveuser')); 

     $.ajax({ 

      url :"sessions.php", 
      type : 'POST', 
      dataType : 'text', 
      data : form, 

      processData : false, 
      contentType : false, 
      success: function(d){ 
       console.log(d);//[error] :Undefined index: username 
      } 
     }); 
    }); 
</script> 
0

你的編碼是correct.Remove過程數據和來自的contentType阿賈克斯將工作

processData : false, 
contentType : false,