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?

0

3 Answers 3

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]);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.