user3227899 user3227899 - 3 months ago 22
Ajax Question

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

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

Answer

You likely want

<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",
      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"] ....
}
Comments