在PHP标记中的JavaScript确认框保持返回TRUE

问题描述:

我试图在php标签内添加javascript代码来处理按钮被按下时它应该确认用户是否真的想要删除图像。在PHP标记中的JavaScript确认框保持返回TRUE

我的问题是,一旦确认框显示 - 它'返回'和'确定'返回true - 它执行代码从数据库中删除图像的任何方式。

任何人都可以提供任何建议吗?

if (isset($_POST['remove'])) { 
    $imgId = $_POST['imgId']; 

    echo '<script type="text/javascript"> 
     var h = "Are you sure you to delete Image ID: '.$imgId.'"; 

     if (!confirm(h)) { 
      event.preventDefault(); 
     } else {' . 
      mysql_query("DELETE FROM images WHERE img_id='$imgId';") . ' 
     } 

    </script>'; 
} 
+3

你不能把php函数调用到javascript中。您必须通过向服务器发送http请求来触发DELETE查询(可能为ajax)。 – James

+0

它适合我。我得到真实和错误。 –

+0

@bub - 这是第一次确认 - 这是作为一个测试 - 第二次确认总是删除图像,并执行查询 – RandomMath

至于有人建议,在这种情况下,最好的办法就是用JS(在这种情况下,我去为jQuery的),并在自己的PHP文件的PHP调用。在这里,你有HTML的简短摘要:

<a href="#" class="js-removeImg" data-image="10">Remove</a> 

的数据图像值(10)将从PHP采取所以你必须exaclty知道你删除什么样的形象。我通常喜欢为将在任何javascript触发器js-removeImg内部链接的类添加一个“js-”前缀以分隔样式和javascript。

$(document).ready(function(){ 


    $('.js-removeImg').on('click', function(e){ 
     e.preventDefault(); // Disables default click's behaviour 

     var $this = $(this); // Cache current jQuery element 

     var imgID = $this.data('image'); 
     //^Stores the image id we want to handle 
     // The value comes from PHP 

     var deleteUrl = "deleteImg.php"; 
     //^A php file where the "delete" query will be available 
     // As parameter it should accept the image id: $_REQUEST['imageID'] 
     // imageID should be exactly the same with the one inside date object from below 

     var string = "Are you sure you want to delete the image with the id __IMGID__ ?"; 
     // ^Stores the string we want to alert in a nicer way, easy to edit in future  

     var confirm = window.confirm(string.replace('__IMGID__', imgID)); 

     // User clicked "ok" 
     if (confirm) { 
     // So we are going to tell this to the server (php file) 
     $.ajax({ 
      method: 'POST', 
      url : deleteUrl, 
      data : { 
      imageID: imgID 
      }, 
      success : function(data) { 
      console.log(data); 
      // Handle the data according to the answer received from PHP file 
      // E.g : shown an alert which say that is done or not etc 
      } 
     }); 
     } else { 
     // User clicked false 
     } 

    }) 
}); 

以上是帮助您实现任务的jQuery代码。我认为这些评论显然是足够的。

否则,请让我知道是否出了问题。