Button to delete record from database - javascript

Script:
$('.removeVehicle').click(function() {
var $this = $(this),
$row = $(this).parent().parent();
alert($row.attr('data-vehicle-id'));
if (confirm("Delete vehicle? ") == true) {
$.post("removevehicle.php", {Id: $row.attr('data-vehicle-id')});
};
});
HTML/PHP:
<?php while ($row = $products->fetch_assoc()) { ?>
<tr data-vehicle-id="<?= $row['Vehicle_ID']?>">
<td class="VRM"><?= $row['VRM']; ?></td>
<td class="Make"><?= $row['Make']; ?></td>
<td class="Model"><?= $row['Model']; ?></td>
<td class="Colour"><?= $row['Colour']; ?></td>
<td class="Mileage"><?= $row['Mileage']; ?></td>
<td class="Advertised Price">£<?= $row['Advertised_Price']; ?></td>
<td class="Date of Registration"><?= $row['Date_of_Registration']; ?></td>
<td class="HPi Status"><?= $row['HPI_Status']; ?></td>
<td class="actions">
<button class="editLine">Edit line</button>
<button class="saveLine hide">Save line</button>
<button class="startSale" onclick="div_showSale()">Start Sale</button>
<button class="removeVehicle"><img id="trash" src="images/trash.png" alt="Delete Vehicle" height=20 width=20></button>
</td>
</tr>
<?php } ?>
removevehicle php:
<?php
require 'config/init.php';
if (isset($_SESSION['myusername'])) {
$mysqli = new mysqli($db['hostname'], $db['username'], $db['password'], $db['database']);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$queryStr = "DELETE FROM VEHICLE WHERE Vehicle_ID = '" . $_POST['Id'] . "'";
$query = $mysqli->query($queryStr);
}
Works up to the point of the alert with the vehicle ID (correct vehicle ID is alerted). Essentially all I need to do is delete the vehicle/record from the database - any better suggestions or how to get the current method working?
Once I've got this working, I'll change the MySQLi query to counteract injection (it's not live yet).

obtain your data attribute information using .data() . Also return your PHP results and dump it to the console. Lastly, check your console for errors. Use this instead:
PHP:
$query = $mysqli->query($queryStr);
echo $query;
JS:
$('.removeVehicle').click(function() {
var $this = $(this),
$row = $(this).parent().parent();
var vehicle_id = $row.data("vehicle-id");
if (confirm("Delete vehicle? ") == true) {
$.post("removevehicle.php", {Id: vehicle_id}, function(result) {
console.log(result);
});
}
});

I think it the issue is with the sql query and wrapping the vehicle_id in quotes?
If you need to delete the row after you'll want to do it in a callback like this:
$.post("removevehicle.php", {Id: $row.attr('data-vehicle-id')}, function() {
// delete the row
});

Related

Ajax request doesn't return a response

I need a little help for my ajax request. I think i don't get the good value but i have tried more methods, without success.
The purpose is when we click on Info client, another array is displayed with more info. But I always have the last id added and not the id's clicked's row.
My HTML :
<div>
<table id="list_client" border=1>
<tr>
<td>#</td>
<td>Nom</td>
</tr>
<?php
require 'config.php';
$clients = $db->query('SELECT * FROM client');
foreach ($clients as $client) : ?>
<tr id="<?php echo $client["id_client"]; ?>">
<td><?php echo $client["id_client"]; ?></td>
<td><?php echo $client["nom_client"]; ?></td>
<td><button name="info" id="info" type="button" onclick="display_info(<?php echo $client['id_client']; ?>);">Info client</button></td>
<td><button type="button" onclick="hide_info(<?php echo $client['id_client']; ?>);">Masquer client</button></td>
<?php endforeach; ?>
</table>
</div>
My JavaScript and Ajax request:
function display_info() {
$("#info").click(function () {
var datas = {
action: "read",
id_client: $("#id_client").val(),
};
$.ajax({
type: "GET",
url: "function.php",
async: true,
data: datas,
dataType: "json",
cache: false,
}).done(function (result) {
console.log("result");
$("#result").text("response : " + JSON.stringify($result));
});
});
}
#result is a div besides the array. (to test)
My PHP function :
function read() {
global $db;
$id_client = $_GET['id_client'];
$client = "SELECT * FROM client WHERE id_client = '$id_client'";
$query = $db->prepare($client);
$query->bindValue(':id_client', $id_client, PDO::PARAM_INT);
$query->execute();
$result = $query->fetch();
echo json_encode($result);
}
I think I am close but no idea what I did wrong.
Issues:
#1 <tr id="<?php echo $client["id_client"]; ?>">
In the above code, how will you dynamically get the id of the client when trying to use it in Javascript?
#2 <td><button name="info" id="info" type="button" onclick="display_info(<?php echo $client['id_client']; ?>);">Info client</button></td>
Above code will make all buttons have same id which is info. id needs to unique per HTML element.
#3 id_client: $("#id_client").val(),.
There is no element with id as id_client.
#4 function display_info() { $("#info").click(function () {.
You are attaching an onclick as well as a click event listener which is not required. Do either of them and not both but I would recommend the latter one.
#5 $client = "SELECT * FROM client WHERE id_client = '$id_client'";
You aren't preparing the query here with a placeholder but rather just adding the retrieved id in the query which is very unsafe since we can't trust user input.
#6 You also missed a closing tr tag.
Solution:
For issue #1, no need to attach an id attribute to a tr tag at all.
For issue #2, make info a class name instead of the id and remove onclick as it isn't needed.
For issue #3, we would get the id_client value from the data-id attribute which we will attach to the respective info button.
For issue #4, encapsulating click event listener inside display_info is not needed. We can directly attach the listener.
For issue #5, we will add a placeholder for id_client to properly bind our primitive value inside the query.
For issue #6, we will add a closing tr tag.
Snippets:
Frontend:
<div>
<table id="list_client" border=1>
<tr>
<td>#</td>
<td>Nom</td>
</tr>
<?php
require 'config.php';
$clients = $db->query('SELECT * FROM client');
foreach ($clients as $client):
?>
<tr>
<td><?php echo $client["id_client"]; ?></td>
<td><?php echo $client["nom_client"]; ?></td>
<td><button data-id="<?php echo $client["id_client"]; ?>" type="button" class="info">Info client</button></td>
<td><button type="button" class="hide_client" data-id="<?php echo $client["id_client"]; ?>">Masquer client</button></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<script>
$(".info").click(function(){
var datas = {
action: "read",
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "GET",
url: "function.php",
data: datas,
dataType: "json",
cache: false,
}).done(function(result) {
console.log("result");
$("#result").text("response : " + JSON.stringify($result));
});
});
$('.hide_client').click(function(){
let client_id = $(this).attr('data-id');
// do your thing here
});
</script>
Backend:
<?php
function read() {
global $db;
$id_client = $_GET['id_client'];
$query = $db->prepare("SELECT * FROM client WHERE id_client = :id_client");
$query->bindValue(':id_client', $id_client, PDO::PARAM_INT);
$query->execute();
$result = $query->fetch();
echo json_encode($result);
}
Not sure if that's the error you're having, but
$client = "SELECT * FROM client WHERE id_client = '$id_client'";
should probably read
$client = "SELECT * FROM client WHERE id_client = :id_client";
as the binding of the prepared statement doesn't work otherwise.
Other than that: Can you check which results you get from your select query and if that's the result you expect?
you are giving the clientid over to the function display_info, you don't need to read it out with jquery... just change
function display_info() {
to
function display_info(clientid) {
and change the
var datas = {
action: "read",
id_client: $("#id_client").val(),
};
to
var datas = {
action: "read",
id_client: clientid,
};

How do I pass multiple variables to function within PHP statement?

Trying to call function Sel_item and pass it the fieldname1 variable as well as the id. The passing of the id works fine, but as soon as I try to pass the fieldname1, it dies. Basically trying to pass the id and the name of the person in mysql database to another function.
$id = $row["id"];
$fieldname1 = $row["person_name"];
$fieldname2 = $row["check_in_butt"];
$fieldname3 = $row["date_time"];
$str = "";
if($fieldname2 == true) $str = "checked";
echo '<tr>
<td>'.$fieldname1.'</td>
<td><input type="checkbox"'.$str. 'onclick="Sel_item('.$id.,.$fieldname1.')" </td>
I usually make it like this. Work for me
<?php
$id = $row["id"];
$fieldname1 = $row["person_name"];
$fieldname2 = $row["check_in_butt"];
$fieldname3 = $row["date_time"];
$str = "";
if($fieldname2 == true) $str = "checked";
?>
<tr>
<td><?= $fieldname1 ?></td>
<td><input type="checkbox" <?= $str ?> onclick="Sel_item('<?= $id ?>', '<?= $fieldname1 ?>')"></td>
</tr>

How to continue keeping the checkbox in checked position after refreshing the page

I have a little trouble with my PHP, js code. When I submit form page is reloading but input checkbox isn't in checked mode, but I need is.
I think maybe I need to get parameter from URL and then compare it with the DOM element and after that set checked mode for input?
PHP code:
if(isset($_GET['user_id'])) {
try {
$PDO_connection = new PDO($dsn, $user, $password, $opt);
$queryForUserInfo = "SELECT position, dateOfBirth, rank, tellNumber, worker_id
FROM workers
WHERE user_id = :id";
$sth = $PDO_connection->prepare($queryForUserInfo);
$sth->bindParam(":id", $_GET['user_id'], PDO::PARAM_STR);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$queryForComeAndReturnUserInfo = "SELECT date_come, date_return
FROM outside_records
WHERE worker_id = {$result[0]['worker_id']}
ORDER BY date_return DESC";
$sth1 = $PDO_connection->prepare($queryForComeAndReturnUserInfo);
$sth1->bindParam(":id", $_GET['user_id'], PDO::PARAM_STR);
$sth1->execute();
$outsideSchedule = $sth1->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e){
echo $e->getMessage();
};
}
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="get" id="listOfUsers_form">
<!--just for getting id to make db query-->
<?php foreach ($AllUsers as $user):?>
<tr class='usersList'>
<td><input type='checkbox' name='user_id' value='<?php if(isset($user)){echo $user['user_id'];}?>'></td>
<td><?php echo $user['name'];?></td>
<td><?php echo $user['surname'];?></td>
<td><?php echo $user['position'];?></td>
</tr>
<?php endforeach; ?>
</tbody>
</form>
js code:
<script>
$(document).ready(function(){
let row = $('#colorful_row').html();
if(row == "Відсутній на робочому місті") {
$("#status").css("background-color", "red");
} else if (row == "На робочому місці") {
$("#status").css("background-color", "lightgreen");
} else {
$("#status").css("background-color", "white");
}
$(".usersList td input:checkbox").on("change", function(){
$(this.attr("checked", "checked"));
$("#listOfUsers_form").submit();
});
});
</script>
Thanks, everybody
Use localStorage
Demo
For localstorage saved the boolean value as string .That why we compare with localStorage.getItem("box") == 'true'
$('input').prop('checked', localStorage.getItem("box") == 'true')
$('input').on('change', function() {
window.localStorage.setItem($(this).attr('name'), Boolean($(this).is(':checked')))
})

Update specific row of table of multiple entries

I have a table of customers. Each customer has a first and a last name. The two text fields of the table are editable. So users can update the information when they press Save. The problem is that I cannot get the specific row information,I only get the first row results
I tried to match to the names with the input field but I had no success.
<?php foreach($customer as $each){ ?>
<td class="first_name" id="first" contenteditable="true"><?php echo
$each['first_name']; ?></td>
<td class="last_name" id="last" contenteditable="true"><?php echo
$each['last_name']; ?></td>
<td > <button type="button" onclick="save('<?php echo $each['first_name'];?
>','<?php echo $each['last_name'];?>');" >Save</button></td>
<? } ?>
<script type="text/javascript">
function save(first,second) {
<?php foreach($customer as $each){?>
var first_name = "<?php echo $each['first_name']?>";
var last_name = "<?php echo $each['last_name']?>";
if (first_name==first && last_name == second){
var fname = document.querySelectorAll(".first_name");
console.log(fname[0]);
}
<?php } ?>
}
</script>
You would have to use a different query selector. Assign a classname or an attribute to the elements you want to select (e.g name for querying with .name) then querySelectorAll method will return an array of the elements that matched your query.
The main problem that I see is that you create unnecessary foreach loop inside a javascript function using php.
You can dynamically create your table and the contents inside it, that's fine. But the javascript does not care about that and you should not create javascript with php. So I would do it this way.
I wrap the td's in tr's cause i'm assuming you are putting that data in tr.
<?php foreach($customer as $each){ ?>
<tr class="customer-row">
<td class="first_name" contenteditable="true"><?php echo
$each['first_name']; ?></td>
<td class="last_name" contenteditable="true"><?php echo
$each['last_name']; ?></td>
<td><button type="button" class="save">Save</button></td>
</tr>
<? } ?>
Then outside the php foreach loop i would create my script.
<script type="text/javascript">
var saveBtn = document.querySelectorAll(".save");
for(var i = 0; i < saveBtn.length; i++) {
// attach click event to every button.
saveBtn[i].addEventListener("click", function() {
var _this = this;
var _tr = _this.closest(".customer-row");
var fname = _tr.querySelector(".first_name").innerText;
var lname = _tr.querySelector(".last_name").innerText;
console.log("Name: ", fname + " " + lname");
// below you can implement your check name logic...
}
}
</script>
I'm not 100% sure if my js will not throw errors, but it should give you an indication that you should separate your server-side from client-side logic.

jquery how to refresh the table without refreshing the page?

i created a table with the help of kendoGrid data table plugin in which i perform a delete after the delete table sholud get reload and do not the show the deleted user but table doesnot reload and still showing the user in table when i refresh the page the user details will be gone i have tired the following code but it is not working
Note:delete operation is working properly
<head>
<script>
$(function () {
$("#example").dataTable();
})
</script>
<script>
$(document).ready(function () {
$("#example").kendoGrid({dataSource: {
pageSize: 10
},
editable: "popup",
sortable: true,
filterable: {
extra: false,
operators: {
string: {
contains: "Contains",
startswith: "Starts with"
}
}
},
pageable: true,
});
});
</script>
<script>
function deleteuser(obj) {
var uid = obj.id;
var uname = obj.name;
if (confirm("This user '" + uname + "' maybe using some other events, Are you sure to delete this user?")) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
//alert(xmlhttp.responseText.trim());
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//alert(xmlhttp.responseText.trim());
if (xmlhttp.responseText.trim() == 'deleted') {
alert('This user "' + uname + '" succesfully deleted');
$('#example').data('kendoGrid').dataSource.read();
} else
alert('Error : user cannot deleted');
}
}
var url = "deleteuser.php?id=" + uid;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div>
<table id="example">
<thead>
<tr>
<td>Action</td>
<td>Name</td>
<td>Username</td>
<td>Email</td>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * from registration";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><button class="btn btn-danger btn-xs" id="<?php echo $row['user_id'] ?>" onClick="deleteuser(this);" name="<?php echo $row['first_name'] ?>" title="Delete"><i class="fa fa-trash-o"></i></button></td>
<td><?php echo $row['first_name'] ?></td>
<td><?php echo $row['user_name'] ?></td>
<td><?php echo $row['email'] ?></td>
<?php
}
?>
</tr>
</tbody>
</table>
</div>
</body>
deleteuser.php
<?php
session_start();
$id = $_GET['id'];
include("../model/functions.php");
$table = "registration";
$condition = "user_id=" . $id . "";
$delete = Deletedata($table, $condition);
if ($delete === TRUE) {
echo'deleted';
} else {
echo 'not deleted';
}
?>
You are not be able to update the table data as is because you have not defined where the table gets the data. The can either refresh the entire page, or create a datasource with a transport & url that you can use to get the data.
When you populate the table server side:
<tbody>
<?php
$sql = "SELECT * from registration";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><button class="btn btn-danger btn-xs" id="<?php echo $row['user_id'] ?>" onClick="deleteuser(this);" name="<?php echo $row['first_name'] ?>" title="Delete"><i class="fa fa-trash-o"></i></button></td>
<td><?php echo $row['first_name'] ?></td>
<td><?php echo $row['user_name'] ?></td>
<td><?php echo $row['email'] ?></td>
<?php
}
?>
</tr>
</tbody>
There is nothing for the table to refresh.
You need to add a source of data for the table to get the data from.
Ordinarily, I define the datasource for the grid separate from the grid definition itself.
As an example:
var gridDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "someurl/to/my/data"
}
},
schema: {
model: { id: "user_id" }
}
});
Then you can define your table something like this:
var jgrid = $("#example").kendoGrid({
columns: [
{
field: "first_name",
title: "First Name"
},
{
field: "user_name",
title: "User Name",
},
{
field: "email",
title: "Email"
}
],
dataSource: gridDataSource
}).data("kendoGrid");
$('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();

Categories

Resources