Search code examples
javascriptphpjqueryarraysarray-push

Passing array to hidden input and retrieve array with elements on different indexes


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?


Solution

  • 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]);