user3227899 user3227899 - 4 months ago 40
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.

var post_id="<?php echo $userIdRow['post_id']; ?>";
var datastring='post_id='+post_id;
function submitdata() {
success:function(html) {
return false;

And delete.php is


// 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);
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

<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() {
       function(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() {
      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

  $id = $_REQUEST["post_id"] ....