admin管理员组

文章数量:1425701

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. 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. For exemple i can have 5 row's on each row 1 of each input . So the result will id=1 DepId=3456 , id =2 DepId = 5432 and so on.

$('#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);
        }, 
        plete : function(data, textStatus, jqXHR){

        }
});
});

Here i handle the ajax post.

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.

The php files looks like this :

//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.

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. 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. For exemple i can have 5 row's on each row 1 of each input . So the result will id=1 DepId=3456 , id =2 DepId = 5432 and so on.

$('#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);
        }, 
        plete : function(data, textStatus, jqXHR){

        }
});
});

Here i handle the ajax post.

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.

The php files looks like this :

//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.

Share Improve this question asked Mar 9, 2015 at 14:53 Andrei KapAndrei Kap 532 silver badges9 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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. So without additional hustle you just put it as data in your ajax function like this:

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:

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.

$(..).serializeArray() will return something like

[
  {
    "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.

    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

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.

$(..).serializeArray() will return something like

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

So use this function on the PHP side, to format it back to the normal $_POST structure.

    $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;
                }

本文标签: javascriptSerialize forminput39s with same nameStack Overflow