2

I have some fields that gets created automatically on click by javascript in the backend. Every field contains a delete button to remove the field, now I need to make sure the PHP code retrieves the deleted fields and delete them from the database. So what I am doing is, I am adding a hidden input to the form and whenever some field gets removed the id of that field is pushed in the hidden input as an array. When I retrieve it in php I will get it like this:

array (size=1)
  0 => string '13,14' (length=5)

instead of the wanted

array (size=2)
    0 => string '13' (length=2)
    1 => string '14' (length=2)

Javascript:

$(wrapper).on("click", ".RemoveField", function(e) {
    var advantageId = $(this).siblings('.advantageId').val();
    var productId = $(this).siblings('.productId').val();
    e.preventDefault();

    deleteAdvantages.push(advantageId);

    $("input[name='deleteAdvantageId[]']").val(deleteAdvantages);

    $(this).parent('div').remove();
    x--;
})

And with PHP I am retreiving the post of the hidden input. Next to that are there also tips perhaps for the security of this?

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
DaViDa
  • 641
  • 1
  • 8
  • 28

3 Answers3

3

You can do that in PHP with the function explode. What this function does is split a string into an array by delimiter so in your case, add:

$array = explode(',', $arrayThatHasTheString[0]);
Lost F.
  • 410
  • 3
  • 15
2

To get an array, you need to submit an array of input values, instead you are submitting a comma separated string as the value.

So 1 solution is to split the string in the server side using PHP like

<input name="deleteAdvantageId" type="hidden" />

$("input[name='deleteAdvantageId']").val(deleteAdvantages);

then

$ids = $_POST['deleteAdvantageId']
$array = explode(",", $ids);
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

You can't submit a hidden array, keep your array at JS level and then submit it along with your Ajax request:

$.ajax({type: "POST", url: "m_url.php", data: {some_data, array: deleteAdvantages}, success: function (data) {...
 }
});

PHP will catch this as:

$_POST[array] => Array ( 
  [0] => 1
  [1] => 34
  [2] => 56
  [3] => 78 
)

Otherwise you will need to explode your input in order to translate that string into an array...

Solrac
  • 924
  • 8
  • 23