0

I'm using Ajax to delete images from my page. Ajax call works well when I delete the first image on the list, and it works when the second is also deleted and so on. However, when I try to delete from the middle, bottom or any image that's not first on the list the ajax request fails and instead the form is submitted and returns error. I don't know why I can't delete any other image except the first on the list. Please help me with a fix. My code is below:

JS

 <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
        <script>
            $(document).ready(function(){
                $('#delform').on('submit', function(e){
                    e.preventDefault();
                    var wid = $('#wid').val();
                    $.ajax({
                        type: "POST",
                        url: 'delete-photo.php',
                        data: {wid: wid},
                        success: function(data){
                            alert("Image Deleted Successfully.");
                            location.reload();
                        }
                    });
                    return false;
                });
            });
        </script>

FORM

<form id="delform">
        <input type="hidden" name="wid" id="wid" value="<?php echo $wid; ?>">
        <input type="submit" name="submit" class ="del-Pic top-50 bottom-0" value="Delete">
        </form>
  • Can you please show an example of markup listing multiple images to choose to delete from? Keeping in mind [Does ID have to be unique in the whole page?](https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page) – Taplar Feb 04 '20 at 18:30
  • Also: [Converting repeating ids to classes](https://stackoverflow.com/questions/59887834/getting-the-value-of-the-input-field-using-jquery/59888053#59888053) – Taplar Feb 04 '20 at 18:33
  • ID is meant to be unique per element. You have multiple elements with same ID. When you try to access an element with ID while there are several with same ID the first one is always selected... hence your issue. Use classes. – Nawed Khan Feb 04 '20 at 18:40
  • The IDs are unique. I don't know how to post my multiple image code here since the comment box only allows limited character. All IDs are gotten from db. wid is actually the id value from db and they are all unique. – Louis Web Solutions Feb 04 '20 at 18:45
  • @Nawed, I'll try classes – Louis Web Solutions Feb 04 '20 at 18:46
  • So you have multiple input pairs within one single form, with unique ids? I see the php setting the `value=""`, but that `id="wid"` appears static – Taplar Feb 04 '20 at 18:47
  • @Taplar, I see my mistake now. Thanks for the help and thanks Nawed, classes did the trick. – Louis Web Solutions Feb 04 '20 at 18:49

0 Answers0