使用$ .ajax删除帖子

I am new to $.ajax and don't know so much and i have following button to delete user post by article ID

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

When click this button then following $.ajax process running.

<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

<?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?

The reason is pretty simple. You should change your request type to GET/DELETE instead of POST. In PHP you expect GET request but in AJAX you send POST request

Change:

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

to

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

in 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. POST should create an object and GET should retrieve it. It may be confusing at first time but it's good practicet specially used in REST APIs. The other one would be UNLINK if you wanted to remove relationship between objects.

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

<?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

<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 !!

You likely want to not only match the "GET" you use in your PHP but also add the ID to the button

<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"

$(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?

Using ajax DELETE with error handling

$(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

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

Follow @roberts advise and also:

You should have a way to handle errors eg.

to your ajax code add this:

    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:

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.