I am new to Node JS. I am trying to be able to delete records from a database dependent on which button is clicked. I believe it is possible through AJAX by getting the attribute but not entirely sure how to be done.
I am using MySQL and Handlebars and the template engine
Here is my code:
Handlebars:
<tbody>
{{#each data}}
<tr>
<td>{{this.name}}</td>
<td><a data-id="{{ this.id }}" class="btn btn-danger">Delete</a></td>
</tr>
{{/each}}
</tbody>
jQuery
$(document).ready(function () {
$("td a").each(function () {
$(this).click(function () {
var id = $(this).attr("data-id");
});
});
});
MySql:
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "node"
});
↓
con.query(`DELETE FROM NodeSQL WHERE id='${id}';`, function (err, result) { ?????
if (err) throw err;
});
This should fix your query.
let id = 123;
con.query(`DELETE FROM NodeSQL WHERE id=?;`,req.params.id, function (err, result) {
if (err) throw err;
});
The main problem you are running into is that frontend javascript and backend javascript(node) are running in different environments and can not share memory. You will need to use something like express.js to create a REST API. Then you can use fetch or axios to communicate to that API.
//FRONTEND ON BUTTON CLICK
axios.post('/api/delete/123');
//BACKEND
const express = require('express')
const app = express()
const port = 3000
const mysql = require('mysql')
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "node"
});
app.post('/api/delete/:id', (req, res) => {
con.query(`DELETE FROM NodeSQL WHERE id=?;`,id, function (err, result) {
if (err) throw err;
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`))