简体   繁体   中英

My page still reload after delete with XMLHttpRequest

Iam trying to delete an image from my page and from the database without reloading the page.

html

   <div class ="thumbnail">
            <div class="gallery-box" id="Display">
                <!-- Thumbnail image -->
                <?php if (isset($image->thumbnailUrl)) echo '<img src="' . htmlspecialchars($image->thumbnailUrl, ENT_QUOTES, 'UTF-8').'">'; ?>
                <a href="#" onClick="deleteSingleImage('<?php echo htmlspecialchars($image->id, ENT_QUOTES, 'UTF-8'); ?>')" class="caption simple-caption delete-single-image">
                <span class="glyphicon glyphicon-trash"> Delete</span>
                </a>
            </div>
        </div>

javascript

function deleteSingleImage(id)
{
  var xmlhttp;
  if (id=="")
    {
        document.getElementById("Display").innerHTML="";
        return;
    }
  if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
  else
  {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
          window.location.reload()

        }
  }
      xmlhttp.open("GET", url + "/album/deleteimage/"+id,true);
      xmlhttp.send();

}

php

public function deleteImage($image_id)
{
  $sql = "...."
  //code to delete the image from database
}

My image is deleted from my database.

The image disappears from the page.

Delete link get the correct ID.

But the page is reloaded when I make a deletion. What's wrong? How do I delete without reloading the page?

You are reloading page after ajax response.

Try this:

    function deleteSingleImage(id)
{
  var xmlhttp;
  if (id=="")
    {
        document.getElementById("Display").innerHTML="";
        return;
    }
  if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
  else
  {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
          //Remove the image element from DOM

        }
  }
      xmlhttp.open("GET", url + "/album/deleteimage/"+id,true);
      xmlhttp.send();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM