admin管理员组

文章数量:1399145

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?

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?

Share Improve this question asked Aug 29, 2016 at 12:57 user3227899user3227899 652 silver badges9 bronze badges 3
  • var post_id="<?php echo $userIdRow['post_id']; ?>"; i am sure for each record id will be different. so this code will not always give you correct id and $_GET need to be change to $_POST – Death-is-the-real-truth Commented Aug 29, 2016 at 12:59
  • 2 for a POST, use $_POST ... $_GET is for GET – Jaromanda X Commented Aug 29, 2016 at 12:59
  • Add an error handler to the Ajax call, look at the network request, look at the server logs. Somewhere you should have an error message that tells you the problem. – epascarello Commented Aug 29, 2016 at 13:00
Add a ment  | 

4 Answers 4

Reset to default 4

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

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

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.

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.

本文标签: javascriptDelete post using ajaxStack Overflow