简体   繁体   English

序列化表单 - 具有相同名称的输入

[英]Serialize form - input's with same name

I have the followin code : 我有以下代码:

<form id="sendObj">
        <table class="no-border hover list">
          <tbody class="no-border-y">';
            while($pendingTransfers = mysql_fetch_assoc($getPending)){
                $id = $pendingTransfers['id'];
                echo '
            <tr class="items">
              <td style="width: 10%;"><span class="label label-primary">'.$counter++.'</span></td>
              <td class="text-left"><p>'.$pendingTransfers['NumarInventar'].'</p></td>
              <td class="text-left"><p><strong>'.$pendingTransfers['DenumireArticol'].'</strong></p></td>
                <input type="hidden" name="id" value="'.$pendingTransfers['id'].'" />
                <td class="text-center"><input type="hidden" name="depID" class="getDep" data-placeholder="Selecteaza destinatie" />  <i style="color:red" title="Sterge din lista" onclick="deleteLista('.$pendingTransfers['id'].');" class="text-right fa fa-times-circle fa-lg"></i></td>
            </tr>';}
                echo '
           </tbody>
        </table>
            </form>     
<div class="text-center"><button id="BtnSendObj" type="submit" class="btn btn-primary btn-success"><i class="fa fa-check color-inverse fa-lg"></i> Finish transfers</button></div>

The above code brings the inserted DB id for each record and on each row in the above table an select option from wich the user can chose some value. 上面的代码为每个记录和上表中的每一行带来了一个select id选项,用户可以从中选择一些值。 When user finishes , he will press the button " Finish transfers" and all the inputs must be serialized. 当用户完成时,他将按下“完成传输”按钮,并且必须序列化所有输入。 The problem is that i have multiple inputs with same name and i cannot group them all as i can use them later in PHP. 问题是我有多个具有相同名称的输入,我无法将它们全部分组,因为我稍后可以在PHP中使用它们。 For exemple i can have 5 row's on each row 1 of each input . 例如,我可以在每个输入的每一行上有5行。 So the result will id=1 DepId=3456 , id =2 DepId = 5432 and so on. 因此结果将是id = 1 DepId = 3456,id = 2 DepId = 5432 ,依此类推。

$('#BtnSendObj').on('click', function(event) {
    event.preventDefault();
    var data;
    var a = $('#sendObj').serializeArray();

    $.each(a, function () {
    var depID = $('input[name=depDestinatie]').serializeArray();
    var id = $('input[name=id]').serializeArray();

     data =[{"id":id, "depID":depID}];  
    }); 

    //The above will output something like :
    // [Object]0: Object
    //depId: Array[4]0: Object1: Object2: Object3: Object...
    // id: Array[4]0: Object1: Object2: Object3: Object

    // Like this i cannot handle them togerther in PHP.
    // I think it should look like an array of objects so like this i would   //be able to acces them easly , i think that both id's should be in same object //, but this is were i dont know how to proceed.
    $.ajax({
        url: 'subpages/data/transferObjects.php',
        data: {data: data},
        type: 'POST',
        success:function(data, textStatus, jqXHR){
            console.log('AJAX SUCCESS');
            console.log(data);
        }, 
        complete : function(data, textStatus, jqXHR){

        }
});
});

Here i handle the ajax post. 在这里我处理ajax帖子。

What i want to achieve it's to send the data to a php file where i will update DB with the values from the form. 我想要实现的是将数据发送到php文件,我将使用表单中的值更新DB。

The php files looks like this : php文件看起来像这样:

//some connection 
        if(isset($_POST['data']))
    {
    $updateObjects = mysql_query("UPDATE transactions SET IDDepartamentDestinatie = '$_POST['depID'] WHERE id = '{$_POST['id']}'");

    }

But like this it will only update the last record from the form as i dont loop through all inputs. 但是这样它只会更新表单中的最后一条记录,因为我不会遍历所有输入。

If someone has some idee how can i do this , i've tried all examples found about serializeArray or serialize, but didnt worked for me. 如果有人有一些想法我怎么能这样做,我已经尝试了所有关于serializeArray或序列化的例子,但没有为我工作。

For a case like this there is another possibility - name those inputs with [] appended to the name: 对于这样的情况,还有另一种可能性 - 将名称附加[]输入命名为:

<input type="hidden" name="id[]" value="'.$pendingTransfers['id'].'" />
<input type="hidden" name="depID[]" class="getDep" data-placeholder="Selecteaza destinatie" />

Then in your $_POST['id'] and $_POST['depId'] you will automatically have arrays. 然后在$_POST['id']$_POST['depId']你会自动拥有数组。 So without additional hustle you just put it as data in your ajax function like this: 所以没有额外的喧嚣你只需将它作为数据放在你的ajax函数中,如下所示:

data: $.param($('#sendObj').serializeArray())

In PHP you take advantage from the fact that the keys in both arrays are the same for corresponding value pairs: 在PHP中,您可以利用以下事实:两个数组中的键对应的值对相同:

if(isset($_POST['depID'])){
    foreach($_POST['depID']) as $k => $v){
        mysql_query("UPDATE transactions SET IDDepartamentDestinatie = '$v' WHERE id = '{$_POST['id'][$k]}'");
    }
}

Also bear in mind that $_POST values should be sanitized with mysql_real_escape_string, better yet, use PDO for mysql handling. 还要记住,$ _POST值应该用mysql_real_escape_string进行清理,更好的是,使用PDO进行mysql处理。

$(..).serializeArray() will return something like $(..).serializeArray()将返回类似的内容

[
  {
    "name": "..",
    "value": "..",
  },{
    "name": "..",
    "value": "..",
  },{
    "name": "..",
    "value": "..",
  },...
]

But you want to group two inputs together. 但是你想把两个输入分组在一起。 To do so, you can use a for loop that you increment by 2 after each step. 为此,您可以使用每个步骤后增加2的for循环。

    var data = [],
        serialized = $('#sendObj').serializeArray(),
        i;
    for (i=0; i<serialized.length; i+=2) {
        var tmpObj = {};
        tmpObj[ serialized[i].name ] = serialized[i].value;
        tmpObj[ serialized[i+1].name ] = serialized[i+1].value;
        data.push(tmpObj);
    }

This should send an array to your PHP which you will need to loop 这应该发送一个数组到你需要循环的PHP

if (isSet($_POST['data'])) {
    foreach ($_POST['data'] as $obj) {
        //use $obj['id'] and $obj['depID']
    }
}

Although this should work, n-dru's answer offers a much cleaner way of doing what you want to do. 虽然这应该有效,但是n-dru的答案提供了一种更清洁的方式来做你想做的事情。

$(..).serializeArray() will return something like $(..)。serializeArray()将返回类似的内容

[
  {
    "name": "..",
    "value": "..",
  },{
    "name": "..",
    "value": "..",
  },{
    "name": "..",
    "value": "..",
  },...
]

So use this function on the PHP side, to format it back to the normal $_POST structure. 因此,在PHP端使用此函数,将其格式化回正常的$ _POST结构。

    $aPostRequest = serializedFormDatajQuery2Array(unserialize($_POST)); 

 function serializedFormDatajQuery2Array($serializedArr){
                      $aFormData = array();
                      foreach($serializedArr as $aRow){

                         if(isset($aFormData[$aRow['name']]) && !is_array($aFormData[$aRow['name']])){
                            $sValue = $aFormData[$aRow['name']];
                            $aFormData[$aRow['name']] = array();
                            $aFormData[$aRow['name']][] = $sValue;
                            $aFormData[$aRow['name']][] = $aRow['value'];
                            continue;
                         }

                                    if(is_array($aFormData[$aRow['name']])){
                                                $aFormData[$aRow['name']][] = $sValue;
                                                continue;
                                    }

                      $aFormData[$aRow['name']] = $aRow['value'];
                      }
                                 return $aFormData;
                }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM