PHP标记中的JavaScript Confirm Box保持返回TRUE

时间:2016-01-20 13:32:07

标签: javascript php jquery mysql confirm

我正在尝试在php标签中添加javascript代码,以便在按下按钮时进行处理,它应该确认用户是否确实要删除该图像。

我的问题是,一旦显示确认框 - 它对'cancel'和'ok'都返回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>';
}

1 个答案:

答案 0 :(得分:1)

正如有人推荐的那样,在这种情况下最好的方法是使用JS(在这种情况下我要使用jQuery)并在自己的php文件中进行php调用。这里有一小段html:

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

数据图像值(10)将取自php,因此您必须知道要删除的图像。我通常喜欢为类添加一个“js-”前缀,它将链接到任何javascript触发器js-removeImg中以分隔样式和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代码。我认为这些评论显而易见。

否则,如果出现问题,请告诉我。