使用ajax代码删除上传的图像文件

I want to delete the images that are uploded one by one in php.

I used the following code for displaying the images.On clicking the delete button the image gets deleted from the upload folder.

Code

ImageLap.tpl.php

foreach ( $mainfile as $files ) {
     echo '<img src="'.$files.'" width="100" height="65">';
     echo '<input type="hidden" value="'.$files.'" name="delete_file" />';
     echo '<input type="submit" value="Delete image" />';
 }

ImageLap.php

  if ( array_key_exists ('delete_file', $_POST ) ) {
       $filename = $_POST['delete_file'];
       if ( file_exists ( $filename ) ) {
           unlink( $filename );
           echo 'File '.$filename.' has been deleted';
       }
  }

This code is working well.But the page has to be refreshed on each file deletion. I need a help to delete the files without refreshing the page.I heard that ajax is used for this.But I don't have knowledge in ajax

Please do help me to implement ajax in this code.

Include jquery in your page header. Then replace

echo '<input type="hidden" value="'.$files.'" name="delete_file" />';
echo '<input type="submit" value="Delete image" />';

to

echo '<input type="hidden" value="'.$files.'" name="delete_file" id="delete_file" />';
echo '<input type="button" value="Delete image" onclick="delete_image()"/>';

Then write a javascript function to call ajax.

function delete_image()
{
  var status = confirm("Are you sure you want to delete ?");  
  if(status==true)
  {
    var file = $("#delete_file").val();
    $.ajax({
      type:"POST",
      url:"ImageLap.php",
      data:{file:file},
      success(html){
       alert('Deleted');
      }
    });
  }
 }

Then in php access file as $_POST['file']

I am just giving to a sharp Idea of using AJAX:

Here is your Loop:

foreach ( $mainfile as $files ) {
    echo '<img src="'.$files.'" width="100" height="65">';
    echo '<input type="hidden" value="'.$files.'" name="delete_file" />';
    echo '<input type="button" value="Delete image" onclick="delete_post(<?php echo $YourPrimaryKey; ?>);" />';
}

Here is you JQuery Ajax Code:

function delete_post( id ) {
    m = confirm("Are you sure you want to delete this post?");  
    if( m == true ) {
       $.post('ajax_files/ImageLap.php.php', {post_id:id}, // Set your ajax file path
       function( data ) {
         $('#yourDataContainer').html( data ); // You can Use .load too
       });
    } else {
       return false;
    }
}

Now create a simple Ajax file in which Use $_POST to get the Primary Key ID which you send from ajax call by POST and Use your Delete Query.. I guess no need to explain this.