简体   繁体   中英

No response on AJAX PHP call request

I am writing code, to delete a user from the database when they click the delete button. When the user clicks the button, they run the function "myFunction" which then makes an ajax call to the delete.php page. It should alert when the user is deleted. When I click the button, nothing happens and the user isn't deleted from the database.

This is the script:

<script>
  function myFunction(){
        $.ajax({
          type:'POST',
          url: 'delete.php',
          success: function()
          {
            alert('deleted')
          }


        })
      }

This is delete.php:

<?php 
require_once(__DIR__.'/../includes/db.php');

session_start();

$theuser = $_SESSION['user_data']['user_id'];

if($_POST){
    $stmt = $Conn->prepare ("DELETE * FROM users WHERE user_id =".$theuser);
    $stmt->execute();
}
?>

The DELETE statement you have is:

DELETE * FROM users WHERE user_id = ...

Whereas, the proper DELETE syntax is:

DELETE FROM users WHERE user_id = ...

The key difference being the wildcard you have included. ( Source )

Moving onto the solution:

<?php 
require_once(__DIR__.'/../includes/db.php');

session_start();

$theuser = $_SESSION['user_data']['user_id'];

if ($_POST && $stmt = $Conn->prepare("DELETE FROM users WHERE user_id = ?")) {
  // Bind the prepared statement params
  $stmt->bind_param("i", $theuser); // assumed user_id is an integer
  
  // Execute the $stmt
  if ($stmt->execute() && $stmt->affected_rows > 0) {
    // Successfully executed, and it affected 1 or more rows
  } else {
    // Failed to execute
  }
  
  // Close $stmt handle
  $stmt->close();
}
?>

Beyond this, it would be expected that you validate $theuser , instead of blindly trusting that it contains a valid user_id .

You should also seek to always implement prepared statements. ( Source )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM