0

I was able to link to the database to add data via AJAX "GET", but now I must send another AJAX "POST" request to delete the data from the SQL database. Given the fact that I have no prior knowledge of PHP or SQL, I am struggling mightily with this task. I have tried to send the request using many different parameters, but am finding these attempts to be futile. I have found many tutorials on this using jQuery, but unfortunately I must use plain JavaScript.

PHP:

<?php

$userName = "root";
$password = "";
$dbName = "ToDo";
$server = "localhost";

$db = new mysqli($server, $userName, $password, $dbName);

$sql = "DELETE FROM tasks WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i", $_REQUEST["id"]);
$stmt->execute();

$returnVal = $stmt->affected_rows;
$stmt->close();
$db->close();
echo $returnVal;

JavaScript: (userWaste represents text input added to database via client side js)

const del = (userWaste) => {
    let xhr = new XMLHttpRequest();
    let url = "ToDo/deleteTask.php";
    let params = "?id=" + userWaste;
    xhr.open("POST", url, true);
    xhr.onreadystatechange = () => {
    if(xhr.readyState == 4 && xhr.status == 200){
    let deletedTask = xhr.responseText;
     }
   }
  xhr.send(params);
Dharman
  • 30,962
  • 25
  • 85
  • 135
wall.91
  • 33
  • 5
  • As I see it this question has nothing to do with PHP. Your PHP is working fine, and you are using `$_REQUEST["id"]` which covers both GET and POST. This is only about passing the POST body via AJAX. You could simplify the question by removing the unnecessary parts. – Dharman Nov 09 '19 at 22:39
  • Yes, the php is fine. I included it because I am not sure if I am referencing it properly in my JavaScript. – wall.91 Nov 09 '19 at 23:40

1 Answers1

-1

PHP:

<?php
 header("Access-Control-Allow-Origin: *");
 $servername = "localhost";
 $username = "root";
 $password = "";
 $dbname = "todo";


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$taskId = $_POST['taskId'];

$sql = "DELETE FROM tasks WHERE id=$taskId";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
    $conn->close();
    return true;
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
    $conn->close();
    return false;
}

JS:

  const del = (userWaste) => {
        let xhr = new XMLHttpRequest();
        xhr.open("POST", "test.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
        let params = "taskId=" + 1;
        xhr.onreadystatechange = function() { // Call a function when the state changes.
          if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
            const x = xhr.responseText;
            console.log(x);
          }
        }
        xhr.send(params);
      }

I believe 'userWaste' contains id of record that you want to delete.

Also change "test.php" in xhr.open to your php script url

Gortis
  • 1
  • 3
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Nov 09 '19 at 22:35
  • It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Nov 09 '19 at 22:36
  • this does not seem to work either. Can you explain what the "+1" is meant to do? (in the params variable) – wall.91 Nov 11 '19 at 16:19