0

(If my english is bad I'm from pewdiepieland) I have a problem that itch the hell out of me.

I have a page with a picture gallery. When logged in every picture gets a form where you can change the description or delete the picture. I also have a form where you can add a new picture to the gallery.

If I add a picture or delete/edit an existing one the part of the page where all of the pictures are shown reloads so that the new content is loaded. (since I don't want the whole page to reload and also wants to show a message about what happened, eg. "The picture was successfully uploaded/changed/deleted").

The problem is that the forms inside of the part which were reloaded stops working. I need to reload the whole page if I want to delete or edit another image. (The form for submitting a new picture still works, since it's outside of the "reloaded part of the page")

Do I have to reload the javascriptfile or anything else, or what do I need to do?

Do you guys need some parts of the code to check? It feels like I need to add something to my code to prevent this instead of changing the existing.. but hey what do I know...

Best Wishes and Merry Christmas!

UPDATE << with Simplyfied code:

HTML/PHP

<form id="addimg" role="form" method="POST" enctype="multipart/form-data">
    <input type="file" name="img">
    <input type="text" name="imgtxt">
    <input type="submit" name="gallery-submit" value="Add Image">
</form>

<div id="gallery_content">
    <?php
    $result = mysqli_query($link, "SELECT * FROM gallery");
    $count = 1;

    while($row = mysqli_fetch_array($result)) {
        $filename  = $row['filename'];
        $imgtxt    = $row['imgtxt'];
        $id        = $row['id'];

        echo '<div>';
        echo    '<img src="gallery/' . $filename . '">';
        echo    '<form id="editimg' . $count . '" role="form" method="POST">';
        echo        '<input type="text" name="imgtxt">';
        echo        '<input type="hidden" name="id">';
        echo        '<input type="submit" name="changeimgtxt" data-number="' . $count . '" value="Update" class="edit_img">';
        echo    '</form>';
        echo    '<button class="delete_img" value="' . $id . '">Delete</button>';
        echo '</div>;
    }
    ?>
</div>

JAVASCRIPT/JQUERY

$(document).ready(function() {
    $('#addimg').submit(function(e) {
        e.preventDefault();
        
        gallery('add', '');
    });

    $('.edit_img').click(function(e) {
        e.precentDefault();
        var formNr = $(this).data('number');

        var dataString = $('#editimg' + formNr).serialize();
        gallery('edit', dataString)
    });

    $('.delete_img').click(function(e) {
        e.preventDefault();
        var imgid = $('this').value();

        gallery('delete', imgid);
    });

    function gallery(a, b) {
        if (a == 'add') {
            var dataString = new FormData($('#addimg')[0]);

            $.ajax({
                type: "POST",
                url: "gallery_process.php",
                data: dataString,
                success: function(text){
                    if(text == 'add_success') {
                        - Show success message -
                        $('#gallery_content').load(document.URL + ' #gallery_content');
                    } else {
                        - Show fail message -
                    }
                },
                cache: false,
                contentType: false,
                processData: false
            });

        } else if (a == 'edit') {
            var dataString = b;

            $.ajax({
                type: "POST",
                url: "gallery_process.php",
                data: dataString,
                success: function(text){
                    if(text == 'edit_success') {
                        - Show success message -
                        $('#gallery_content').load(document.URL + ' #gallery_content');
                    } else {
                        - Show fail message -
                    }
                }
            });
        } else if (a == 'delete') {
            var dataString = 'imgid=' + b;

            $.ajax({
                type: "POST",
                url: "gallery_process.php",
                data: dataString,
                success: function(text){
                    if(text == 'delete_success') {
                        - Show success message -
                        $('#gallery_content').load(document.URL + ' #gallery_content');
                    } else {
                        - Show fail message -
                    }
                }
            });
        } 
    }
});

I don't think you need to see my process-file. Any clues?

Community
  • 1
  • 1
Pixeldoris
  • 99
  • 7

2 Answers2

0

Your problem is probably the .click function on add and delete image so change it to $('body').on('click', 'delete_img', function() {// do something});

See Here

Community
  • 1
  • 1
Moses Schwartz
  • 2,857
  • 1
  • 20
  • 32
0

Your problem is that you only hook up the .click() listeners once on "document ready".

When the $(document).ready() callback is executed the gallery has already been filled and you hook up click listeners on the elements that are currently in the DOM. When you reload the gallery it is no longer the same DOM elements and no click listeners are being set up on these ones. There are a multitude of ways you correct this, for example, jQuery .load() takes a complete callback in which you can set up the event listeners. Your sample adapted with this:

$(document).ready(function() {
    var setupGalleryEventListeners = function () {
        $('.edit_img').click(function(e) {
            e.preventDefault();
            var formNr = $(this).data('number');

            var dataString = $('#editimg' + formNr).serialize();
            gallery('edit', dataString)
        });

        $('.delete_img').click(function(e) {
            e.preventDefault();
            var imgid = $('this').value();

            gallery('delete', imgid);
        });
    };

    $('#addimg').submit(function(e) {
        e.preventDefault();

        gallery('add', '');
    });

    setupGalleryEventListeners(); // Setup initial event listeners on page load

    function gallery(a, b) {
        if (a == 'add') {
            var dataString = new FormData($('#addimg')[0]);

            $.ajax({
                type: "POST",
                url: "gallery_process.php",
                data: dataString,
                success: function(text){
                    if(text == 'add_success') {
                        - Show success message -
                        $('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
                    } else {
                        - Show fail message -
                    }
                },
                cache: false,
                contentType: false,
                processData: false
            });

        } else if (a == 'edit') {
            var dataString = b;

            $.ajax({
                type: "POST",
                url: "gallery_process.php",
                data: dataString,
                success: function(text){
                    if(text == 'edit_success') {
                        - Show success message -
                        $('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
                    } else {
                        - Show fail message -
                    }
                }
            });
        } else if (a == 'delete') {
            var dataString = 'imgid=' + b;

            $.ajax({
                type: "POST",
                url: "gallery_process.php",
                data: dataString,
                success: function(text){
                    if(text == 'delete_success') {
                        - Show success message -
                        $('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
                    } else {
                        - Show fail message -
                    }
                }
            });
        } 
    }
});
Hyddan
  • 1,297
  • 15
  • 24
  • That's super logic! I had in mind that I somehow needed to "reload" the js to get the "button to listen", but didn't think about using the eventlistener. Thank you :) I'll try to make it work now! – Pixeldoris Dec 23 '16 at 16:47
  • if I press delete or add multiple times in one row I see that it makes multiple calls to my process_files. Like it's a bunch of different DOMs working all at once. Do you understand what I mean by that and do you know anything to prevent this? @Hyddan – Pixeldoris Dec 26 '16 at 21:39
  • Hard to say without seeing the code (is the sample here still accurate?) but, I see now that I made a mistake in the previous answer - it wasn't intended to have the `#addimg` click listener inside the `setupEventListeners` function. Since this element is not deleted/recreated there will be multiple listeners assigned to it and that would cause what you're seeing. I have updated the answer now, only adding the `#addimg` click listener once. – Hyddan Dec 30 '16 at 17:33
  • I made a new question for the problem with multiple eventlisteners, and I'm currently using one of the answers in that thread. I'll post the link here if you wanna check it out @Hyddan [link](http://stackoverflow.com/questions/41350150/need-eventlistener-for-click-so-that-dynamically-refreshed-buttons-work-but-ac/41350556?noredirect=1#comment69903432_41350556) – Pixeldoris Dec 31 '16 at 01:39