0

I send a request via ajax to delete a file. The first time , ajax handles the request, but the second time not anymorte. i got a "hard refresh"

This is my code:

<?php
if(isset($_POST['deletefile'])) {

        // if is directory -> remove dir
        if(is_dir($_POST['deletefile'])){

        removeDirectory($_POST['deletefile']);      
        exit;

        }
        // else (must be a file) -> unlink file
        else {

        unlink($_POST['deletefile']);
        exit;
        }

}
?>
<div class="myFiles">
 <form class="sfmform" method="post" action="">
        <input type="hidden" name="deletefile" value="<?php echo $dir.'/'.$file; ?>" />
        <input type="submit" class="sfmdelete"  name="delete" value=" " />
 </form> 
 <script>
  $(".sfmform").on('submit',(function(e) {
        e.preventDefault();
            $.ajax({
            url: "",
            type: "POST",
            data:  new FormData(this),

            contentType: false,
            processData: false,
            success: function(response)
            {           
            $('.myFiles').load(document.URL +  ' .myFiles');
            },

       });

    }));
 </script>

 </div> <!-- END myFiles -->

To see immediately when i file has been deleted, i use this line $('.myFiles').load(document.URL + ' .myFiles');

The first delete request goes fine, but the second: he makes a hard refresh and dies in the php loop. I was hoping that after the exit in the php the line $('.myFiles').load(document.URL + ' .myFiles'); was executing but the second time it loads not the <div class="myFiles> anymore.

How can i make this work properly?

Even when i put the js in the ready handler, it does not work! The reason why i use an exit in the php: otherwise the <div class="myFiles"> appears 2 times under each other

Jack Maessen
  • 1,780
  • 4
  • 19
  • 51

1 Answers1

1

You changed the html of .myFiles so everything in it in the second time is dynamically generated . so you need Event binding on dynamically created elements? .. change

$(".sfmform").on('submit',(function(e) {

to

$(document).on('submit' , ".sfmform" , (function(e) {

Note: for me its not a good practice to use $.ajax with the same file url: better for me to make a separate file

Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28