简体   繁体   English

使用$ .ajax删除帖子

[英]Delete post using $.ajax

I am new to $.ajax and don't know so much and i have following button to delete user post by article ID 我是$ .ajax的新手,并且了解的不多,我有以下按钮按文章ID删除用户帖子

<button type="button" onclick="submitdata();">Delete</button>

When click this button then following $.ajax process running. 单击此按钮后,将运行$ .ajax进程。

<script>
    var post_id="<?php echo $userIdRow['post_id']; ?>";
    var datastring='post_id='+post_id;
    function submitdata() {
        $.ajax({
            type:"POST",
            url:"delete.php",
            data:datastring,
            cache:false,
            success:function(html) {
                alert(html);
            }
        });
        return false;
    }
</script>

And delete.php is 和delete.php是

<?php

// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_GET['post_id']) && is_numeric($_GET['post_id'])) {
// get the 'post_id' variable from the URL
    $post_id = $_GET['post_id'];

// delete record from database
    if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
        $userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
        $userPostsQuery->execute();
        $userPostsQuery->close();
        echo "Deleted success";
    } else {
        echo "ERROR: could not prepare SQL statement.";
    }

}
?>

This code not working post not deleted. 此代码不起作用,帖子未删除。 Please how do I do? 请问我该怎么办?

You likely want to not only match the "GET" you use in your PHP but also add the ID to the button 您可能不仅要匹配在PHP中使用的“ GET”,还要将ID添加到按钮

<button class="del" type="button" 
  data-id="<?php echo $userIdRow['post_id']; ?>">Delete</button>

using $.get which matches your PHP OR use $.ajax({ "type":"DELETE" 使用与您的PHP匹配的$ .get或使用$.ajax({ "type":"DELETE"

$(function() {
  $(".del").on("click", function() {
    $.get("delete.php",{"post_id":$(this).data("id")},
       function(html) {
            alert(html);
       }
    );
  });
});

NOTE: Please clean the var 注意:请清洁无功

Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection? htmlspecialchars和mysql_real_escape_string是否可以防止我的PHP代码被注入?

Using ajax DELETE with error handling 结合使用ajax DELETE和错误处理

$(function() {
  $(".del").on("click", function() {
    $.ajax({
      url: "delete.php",
      method: "DELETE", // use "GET" if server does not handle DELETE
      data: { "post_id": $(this).data("id") },
      dataType: "html"
    }).done(function( msg ) {
      $( "#log" ).html( msg );
    }).fail(function( jqXHR, textStatus ) {
      alert( "Request failed: " + textStatus );
    }); 
  });
});

In the PHP you can do 在PHP中,您可以执行

if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
  $id = $_REQUEST["post_id"] ....
}

The reason is pretty simple. 原因很简单。 You should change your request type to GET/DELETE instead of POST. 您应该将请求类型更改为GET / DELETE而不是POST。 In PHP you expect GET request but in AJAX you send POST request 在PHP中,您需要GET请求,而在AJAX中,您发送POST请求

Change: 更改:

type:"POST",
url:"delete.php",
data:datastring,

to

type:"DELETE",
url:"delete.php?" + datastring,

in PHP 在PHP中

if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && !empty($_REQUEST["post_id") {
    $id = $_REQUEST["post_id"];
   // perform delete
}

DELETE is actually the only valid method to delete objects. 实际上,DELETE是删除对象的唯一有效方法。 POST should create an object and GET should retrieve it. POST应该创建一个对象,而GET应该检索它。 It may be confusing at first time but it's good practicet specially used in REST APIs. 乍一看可能会造成混淆,但这是在REST API中专门使用的良好做法。 The other one would be UNLINK if you wanted to remove relationship between objects. 如果要删除对象之间的关系,则另一个为UNLINK。

since you're sending a post request with ajax so you should use a $_POST iin your script and not a $_GET here is how it sould be 因为您要发送带有ajax的发布请求,所以您应该在脚本中使用$ _POST而不是$ _GET,这就是它的灵魂所在

<?php

// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_POST['post_id']) && is_numeric($_POST['post_id'])) {
// get the 'post_id' variable from the URL
    $post_id = $_POST['post_id'];

// delete record from database
    if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
        $userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
        $userPostsQuery->execute();
        $userPostsQuery->close();
        echo "Deleted success";
    } else {
        echo "ERROR: could not prepare SQL statement.";
    }

}
?>

for the JS code 用于JS代码

<script>
    var post_id="<?php echo $userIdRow['post_id']; ?>";
    function submitdata() {
        $.ajax({
            type:"POST",
            url:"delete.php",
            data:{"post_id":post_id},
            cache:false,
            success:function(html) {
                alert(html);
            }
        });
        return false;
    }
</script> 

here i've supposed thqt the give you the real id post you're looking for !! 在这里我应该给您您正在寻找的真实身份证!

Follow @roberts advise and also: 遵循@roberts的建议,也:

You should have a way to handle errors eg. 您应该有一种处理错误的方法,例如。

to your ajax code add this: 在您的ajax代码中添加以下内容:

    error:function(e){
     alert(e.statusText)// if you like alerts
     console.log(e.statusText)// If you like console
   }

You should also check your error logs. 您还应该检查错误日志。 Assuming you use apache2 and linux execute this in terminal: 假设您使用apache2和linux在终端中执行此操作:

tail -f /var/log/apache2/error.log 

This gives you a very elaborate way to code. 这为您提供了一种非常精致的编码方式。 You also eliminate the problem of trial and error. 您还消除了反复试验的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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