0

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?

user3227899
  • 65
  • 2
  • 9

4 Answers4

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"] ....
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

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.

Robert
  • 19,800
  • 5
  • 55
  • 85
  • maybe you should suggest him to change PHP code and use POST instead. Operations such as delete should not be made with GET method. – Robert Aug 29 '16 at 13:02
  • 1
    should not be done with POST either. The best method for it is DELETE. And GET work more similar to DELETE than POST – Robert Aug 29 '16 at 13:03
  • Depends on the API specifications, but you are right. DELETE is suggested method. – Robert Aug 29 '16 at 13:04
  • 1
    Because of your name it looks like I'd be talking to myself – Robert Aug 29 '16 at 13:05
  • i edited all code in your said but article didn't deleted and nothing happen. in console no errors to show – user3227899 Aug 29 '16 at 13:43
  • open browser console go to network filter by XHR request and see the response if there are any errors – Robert Aug 29 '16 at 14:34
1

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

PacMan
  • 1,358
  • 2
  • 12
  • 25
0

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.