2014-02-05 36 views
0

我知道如何正常發送這個表單,並且需要定期提交。然而,我對如何通過.ajax發送多維表單數組感到困惑。通過.ajax發送多維表單數組到PHP準備語句

我的形式:

<form action="week_update.php" id="theform" method="post"> 
<input type="text" name="data[][wednesday_crew]" value=""/> 
<input type="text" name="data[][thursday_crew]" value=""/> 
<input type="text" name="data[][friday_crew]" value=""/> 
<input type="text" name="data[][saturday_crew]" value=""/> 
<input type="text" name="data[][sunday_crew]" value=""/> 

我的PHP:

$stmt = $connection->stmt_init(); 

if($stmt->prepare("UPDATE tableName SET ... = ?, ... = ?,)) { 

// Bind your variables 
$stmt->bind_param('ss', $.., $..,); 

// get the multi array from form 
$returnedData = $_POST['data']; 

//let's loop through it. 
for($i=0;$i<count($returnedData);$i+=2){ 
    $log_dates_ID = $returnedData[$i]['...']; 
    $crew_chief = $returnedData[$i+1]['...']; 
    $stmt->execute(); 
} 

回答

0

如果你做了form serialization應該工作,因爲你只需要在urlencoded的字符串發送到你的腳本

1

這是相對容易的,如果我已經正確理解你。我回答了一個類似於這個問題的問題。

$("#theform").submit(function() { 

    var url = "path/to/your/script.php"; // the script where you handle the form input. 

    $.ajax({ 
      type: "POST", 
      url: url, 
      data: $("#theform").serialize(), // serializes the form's elements. 
      success: function(data) 
      { 
       alert(data); // show response from the php script. 
      } 
     }); 

    return false; // avoid to execute the actual submit of the form. 
}); 
+0

謝謝!在服務器端呢? – user1040259

+0

服務器端 - 如您所說,您的示例中的php有效。因爲這種情況下,將代碼放在一個'path/to/your/script.php'文件中,它將在表單提交中執行。 – Vector

+0

表單正在提交,但數據未被插入到我的數據庫中。任何其他快速的想法?再次感謝! – user1040259

1

你幾乎得到了它,但你輸入元素應該是

<input .... name="data[friday_crew][]" /> 
            ^^-- 

那將產生在'數據爲每個你有類型的副陣列。現在你的將會構建一些醜陋的破壞陣列,這對於遍歷/分析來說是非常難看的。相比之下,上述版本只需要

foreach($_POST['data']['friday_crew'] as $key => $val) { 
    $fri_crew = $val; 
    $sat_crew = $_POST['data']['sat_crew'][$key]; 
    etc... 
}