How to loop array input values given via jquery?

At the start of a page I have:

<input id="input_post_id" type="text" name="varPostId[]" value="">

I then have a series of images and a remove button, then with JS i click on the remove button, I get the image id which i’ve given within a data attribute of the current remove button:

<button type="button" data-thisPostId='<?php echo $val['value']; ?>' class='btn btn-danger rimuovi' onclick='removeIt(this)'>Rimuovi</button>

That call a function which adds to the input val a comma separated list of ID:

function removeIt(e) {
  e.closest(".row").remove();
  var removeThisId = e.getAttribute("data-thisPostId");
  var cur_val = $('#input_post_id').val();
  if(cur_val) {
    $('#input_post_id').attr("value", cur_val + "," + removeThisId);
  } else {
    $('#input_post_id').attr("value",removeThisId);
  }
}

Finally I have a form, when I click submit, then I explode the input val array and then I loop and delete the ids. This php is at the beginning of the page:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['submit_post'])) {
        $imagesToDelete = explode(', ', $_POST['varPostId']);
        foreach($imagesToDelete as $value) {
            wp_delete_attachment($post_to_edit->ID, $value);
            delete_post_meta( $post_to_edit->ID, 'media', $value ); 
        };
    }
}

But if I remove one image (one ID), it is still deleting all the images, even tho i can see in the input val the one ID only I’ve selected.