How do you create a delete button using AJAX?

I want to create a delete button that works with AJAX. I can not find a tutorial or something without jquery. I want to create it with Javascript. I have tried a number of things but that did not go well, I deleted that piece of code because my script didn’t work anymore. I also use PHP and PDO to use my MYSQL database.

I’m new to AJAX. I have already succeeded in showing the data of the database and live search has also succeeded for me with AJAX.

I hope someone can help me to create it and that I can learn from it. So that I can create the add and edit buttons by myself. Thanks in advance!

index.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Ajax</title>
</head>
<body>
<section class="hero is-primary">
    <div class="hero-body">
        <div class="container">
            <h1 class="title">Ajax</h1>
            <h2 class="subtitle">Search Panel</h2>

        </div>
    </div>
</section>
<section class="content">
    <div class="container">
        <form id="userForm" action="" method="post">
            <div class="columns">
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Klantnr</label>
                        <p class="control has-icons-left has-icons-right">
                            <input class="input" type="text" id="klantnr" name="klantnr" placeholder="Klantnr">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Plaats</label>
                        <p class="control has-icons-left has-icons-right">
                            <input class="input" type="text" id="plaats" name="plaats" placeholder="Plaats">
                        </p>
                </div>
                </div>
            </div>

            <div class="columns">
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Naam</label>
                        <p class="control has-icons-left has-icons-right">
                            <input class="input" type="text" id="naam" name="naam" placeholder="Naam">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Telefoon</label>
                        <p class="control has-icons-left has-icons-right">
                            <input class="input" type="text" id="telefoon" name="telefoon" placeholder="Telefoon">
                        </p>
                    </div>
                </div>
            </div>

            <div class="columns">
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Adres</label>
                        <p class="control has-icons-left has-icons-right">
                            <input class="input" type="text" id="adres" name="adres" placeholder="Adres">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                        <label class="label">Label</label>
                    <div class="select">
                        <select>
                            <option>Kredietcode...</option>
                            <option>A</option>
                            <option>B</option>
                            <option>C</option>
                            <option>D</option>
                            <option>E</option>
                            <option>F</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="columns">
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Postcode</label>
                        <p class="control has-icons-left has-icons-right">
                            <input class="input" type="text" id="postcode" name="postcode" placeholder="Postcode">
                        </p>
                    </div>
                </div>
                <div class="column">
                <div class="field">
                    <p class="control">
                        <button id="new" class="button is-primary">New</button>
                    </p>

                </div>
                </div>
            </div>

        </form>

        <form id="searchform" action="getdata.php" method="post">

            <div class="columns  is-centered">
                <div class="column is-one-third is-half">
                    <div class="field">
                        <p class="control has-icons-left has-icons-right">
                            <input class="input" type="text" id="js-customers-search" name="search" placeholder="Search">
                        </p>
                    </div>
                </div>

        </form>


</section>

<section class="content">

    <table>
        <tr>
        <th>Klantnummer</th>
        <th>Naam</th>
        <th>Adres</th>
        <th>Postcode</th>
        <th>Plaats</th>
        <th>Telefoon</th>
        <th>Kredietcode</th>
        </tr>
        <tbody id="js-customers-mount">
        </tbody>
    </table>

</section>

<script src="js/main.js"></script>
</body>
</html>

main.js

var customers = [];
var customersTableElement = document.querySelector('#js-customers-mount');
var customersSearchElement = document.querySelector('#js-customers-search');

var fetchData = async (search = '') => {
  try {
    var request = await fetch(`getdata.php?search=${search}`);

    customers = await request.json();
    renderData();
  } catch (error) {
    console.warn(error);
  }
}

var renderData = () => {
  var rows = ``;

  customers.forEach(customer => {
    var customerJsonString = JSON.stringify(customer);

    rows += `
      <tr>
        <td>${customer.Klantnr}</td>
        <td>${customer.Naam}</td>
        <td>${customer.Adres}</td>
        <td>${customer.Postcode}</td>
        <td>${customer.Plaats}</td>
        <td>${customer.Telefoon}</td>
        <td>${customer.Kredietcode}</td>
        <td>
        <form action="deldata.php" method="post">
          <button data-customer="${customerJsonString}" id="editcustomer" class="button is-primary">Edit</button>
          <form action="deldata.php" method="post">
          <button data-customer="${customerJsonString}" id="deletecustomer" class="button is-danger">Delete</button>
          </form>
        </td>
      </tr>
    `
  });

  customersTableElement.innerHTML = rows;
}

customersSearchElement.addEventListener('keyup', event => fetchData(event.target.value));

document.addEventListener('DOMContentLoaded', () => fetchData());

document.addEventListener('click', event => {
  if (event.target.dataset.customer) {

    console.log(JSON.parse(event.target.dataset.customer))
  }
});

getdata.php

<?php

$servername = "127.0.0.1";
$dbname = "klanten";
$username = "rico";
$password = "papillon";

$connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if ($_GET['search'] !== '') {
    $statement = $connection->prepare('
        SELECT * FROM klanten 
        WHERE Klantnr LIKE :search 
        OR Naam LIKE :search 
        OR Adres LIKE :search
        OR Postcode LIKE :search
        OR Plaats LIKE :search
        OR Telefoon LIKE :search
        OR Kredietcode LIKE :search
    ');

    $statement->bindValue(':search', '%' . $_GET['search'] . '%');
} else {
    $statement = $connection->query("SELECT * FROM klanten");
}

$statement->execute();

$customers = $statement->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($customers);

deldata.php This is the script that I need to delete data.

<?php
//The query that I need.

//DELETE FROM klanten WHERE Klantnr = :Klantnr

?>

For you to be able to delete something, you have to have something to delete. What exactly are you wanting to delete? If you want to add a delete button for a record you have retrieved from the database, then I suggest you make sure you give the element containing the item a unique id which would come from the database record. Then, when your button is clicked, you would make a request to the php page and use a database query to delete based on the record’s unique id. Of course, you will also want to remove the element from the html page using JavaScript after your request successfully deletes the data.

I would start by trying to write the php code which takes a unique id for a record and deletes it. Once you have that working, then you can work on the page which populates the search results and make sure each result has a unique id attribute. Lastly, you will need to add an event listener for the delete button, which when clicked, will use the id to make a delete request to the php page and remove the element if the response received back confirms the database deletion was successful.

1 Like