2016-03-02 60 views
1

我想在不刷新頁面的情況下刪除數據庫中的數據。我的代碼正在工作,但刪除產品後需要刷新頁面。我想是這樣this刪除數據庫中的數據而不重新加載頁面

這裏是我的js代碼:

<script> 
    $(document).on('click', '.delete-it', function() { 
     var id = $(this).attr('delete-id'); 
     bootbox.confirm("Are you sure?", function(result) { 
      if (result) { 
       $.ajax({ 
        type: "POST", 
        async: false, 
        url: "delete_product.php", 
        data: { 
         object_id: id 
        }, 
        dataType: 'json', 
        success: function(data) { 
         location.reload(); 
        } 
       }); 
      } 
     }); 
     return false; 
    }); 
</script> 

和delete_product PHP代碼:

<?php 
// check if value was posted 
if($_POST){ 



    // get database connection 
    $database = new Database(); 
    $db = $database->getConnection(); 

    // prepare product object 
    $product = new Product($db); 

    // set product id to be deleted 
    $product->id = $_POST['object_id']; 

    // delete the product 
    if($product->delete()){ 
     echo "Object was deleted."; 
    } 

    // if unable to delete the product 
    else{ 
     echo "Unable to delete object."; 

    } 
} 
?> 

請告訴我一個方法,使之!

+0

您可以在成功發佈後從頁面中移除html元素。它看起來像你可以利用刪除ID來完成這一點。 – spaniol6

+2

在刪除的成功回調中,發出一個ajax調用,將所有產品從數據庫中取出並將結果放入您的HTML – mhodges

+0

下面是使用delete-id的行:'echo'Delete「; ' –

回答

0

我看不出有什麼地方,你在頁面定向的東西,但是這是我會用什麼:

<script> 
function swapContent(href, url_data, target) { 
    $.ajax({ 
     type: 'GET', 
     cache: false, 
     url: href+'?' + url_data, //add a variable to the URL that will carry the value in your i counter through to the PHP page so it know's if this is new or additional data 
     success: function (data) { // this param name was confusing, I have changed it to the "normal" name to make it clear that it contains the data returned from the request 
      //load more data to "target" value div 
      target.innerHTML = (data); // as above, data holds the result of the request, so all the data returned from your results.php file are in this param but please see below 
     } 
    }) 

} 
    $(document).on('click', '.delete-it', function() { 
     var id = $(this).attr('delete-id'); 
     bootbox.confirm("Are you sure?", function(result) { 
      if (result) { 
     swapContent(base_url, url_data, target) //set variables 
    } 
     }); 
     return false; 
    }); 
</script> 

注:因爲多少AJAX我用的,我把一個ajax功能通過本身