Javascript delete isn't working - javascript

My delete function isn't working.
This is my table with the delete button.
// retrieve table contents
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td class='text-align-center'><input type='checkbox' name='item[]' class='checkboxes' value='{$employeeid}' /></td>";
echo "<td>{$name}</td>";
echo "<td>{$title}</td>";
echo "<td>{$phone}</td>";
echo "<td>{$supplier_name}</td>";
echo "<td>{$created}</td>";
echo "<td>";
// update record
echo "<a href='update_product.php?employeeid={$employeeid}' class='btn btn-info margin-right-1em'>";
echo "<span class='glyphicon glyphicon-edit'></span> Rediger";
echo "</a>";
// delete record
echo "<a delete-employeeid='{$employeeid}' delete-file='delete_product.php' class='btn btn-danger delete-object'>";
echo "<span class='glyphicon glyphicon-remove'></span> Slet";
echo "</a>";
echo "</td>";
echo "</tr>";
}
//end table<br>
echo "</table>";
This is my delete function
// delete single record
$(document).on('click', '.delete-object', function(){
// php file used for deletion
var delete_file = $(this).attr('delete-file');
var id = $(this).attr('delete-id');
var q = confirm("Are you sure?");
if (q == true){
$.post(delete_file, {
object_id: id
}, function(data){
location.reload();
}).fail(function() {
alert('Unable to delete.');
});
}
return false;
});
I got the code from a tutorial that I modified a lot. Everything else is working, except the delete function.
PHP CODE
<?php
// check if value was posted
if($_POST){
// include database and object file
include_once 'config/database.php';
// delete query
$query = "DELETE FROM employeestest WHERE employeeid = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_POST['object_employeeid']);
if($stmt->execute()){
// redirect to read records page and
// tell the user record was deleted
echo "Medarbejderen er slettet.";
}else{
echo "Medarbejderen kunne ikke slettes.";
}
}
?>

Change
var id = $(this).attr('delete-Id');
to
var id = $(this).attr('delete-employeeid');
And, Change $.post to $.ajax as i've given
<script>
$(document).on('click', '.delete-object', function(){
var delete_file = $(this).attr('delete-file');
var id = $(this).attr('delete-employeeid');
var q = confirm("Are you sure?");
if (q == true)
{
$.ajax({url:delete-file,cache:false,success:function(result){
alert('Successfully Deleted');
}});
}
return false;
});
</script>

Maybe you just made grammar mistake
'delete-id' => 'delete-employeeid'

Related

Deleting database data with button in table

I have a search page on my web app which searches for events in my event table in my database. I would like to have it so that there is a delete button at the end of the search result with the ability to delete a database entry but also a pop up alert box before they delete the data.
My search results are displayed with the code below:
if(mysqli_num_rows($result) > 0) {
echo "<br>Result Found: ";
echo "<br><table>";
While($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>Event Number: " . $row['EventID'] . "</td>";
echo "</tr><tr>";
echo "<td>Location: " . $row['Location'] . "</td>";
echo "</tr><tr>";
echo "<td><input type='button' name='Delete' value='Delete' onClick='getConfirmation();'></td>";
}
echo "</table
I'm not too sure what to put in the javascript function. I want it to come up a basic alert box and if the user clicks the okay button then the action will be 'delete.php' and ideally another pop-up come up saying "Record Deleted Successfully". I also need to make sure to get the eventID from the record so that I can delete it successfully. So far for the JS function I have:
<script type = "text/javascript">
<!--
function getConfirmation() {
var retVal = confirm("Are you sure you would like to delete this record?");
if( retVal == true ) {
delete.php
document.write("Record deleted successfully");
}
else {
return false;
}
}
//-->
</script>
I know this is wrong but I am wondering how I can fix this?
Also could I just put it that if they press yes the php executes rather than going to delete.php?
To achieve this, you need to pass eventId in your onclick event as below:
if(mysqli_num_rows($result) > 0) {
echo "<br>Result Found: ";
echo "<br><table>";
While($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>Event Number: " . $row['EventID'] . "</td>";
echo "</tr><tr>";
echo "<td>Location: " . $row['Location'] . "</td>";
echo "</tr><tr>";
echo "<td><input type='button' name='Delete' value='Delete' onClick='getConfirmation(".$row['EventID'].");'></td>";
}
echo "</table>";
and in your JS code, you need to:
1. Get eventId in your js function.
2. Call ajax to delete that event.
3. show success alert after
<script type = "text/javascript">
function getConfirmation(eventId) {
var retVal = confirm("Are you sure you would like to delete this record?");
if( retVal == true ) {
$.ajax({
url: "delete.php",
method: "POST",
data: {eventId: eventId},
success: function (response) {
if(response.status) {
alert("Record Deleted Successfully");
}
}
});
} else {
return false;
}
}
</script>
Also, in your delete.php file, you need to get eventId by $_POST['eventId'] and you can execute delete query. and you need to send back to status. Hope it will help you.

how to delete data from database in php,ajax,javascript(no jquery)

I'm trying to delete data from database but when I click on delete button then its delete the first row not where I'm clicking.
my PHP Code:
<?php
$connect = mysqli_connect("localhost","root","","abu");
if($connect){
$showdata = mysqli_query($connect,"SELECT * FROM dealers");
if(mysqli_num_rows($showdata)>0){
$i = 1;
while($rows = mysqli_fetch_assoc($showdata)){
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$rows["dealer_name"]."</td>";
echo "<td><button onclick='deleteproduct()' class='delete'>Delete</button><input type='hidden' id='productid' vlaue='".$rows["id"]."'></td>";
echo "</tr>";
$i++;
}
}else {
echo "<center><i>No Dealers to show</i></center>";
}
}
?>
And this is my ajax code:
function deleteproduct(){
if(window.XMLHttpRequest){
http = new XMLHttpRequest();
}else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
http.onreadystatechange = function(){
if(http.readyState == 4 && http.status == 200){
document.getElementById("alerts").innerHTML = http.responseText;
}
}
var delid = document.getElementById("productid").value;
var file = "assets/php/addproduct_deletedata.php";
var senddata = "productid="+delid;
http.open("POST",file,true);
http.setRequestHeader("content-type","application/x-www-form-urlencoded");
http.send(senddata);
}
I want that when I click on delete button then it delete the row where I clicked not others.
FIRST OF ALL YOU CANNOT ASSIGN THE SAME ID TO MORE THAN ONE ELEMENTS ON A PAGE.
The browser won't mind it but It makes the HTML invalid. You can use class attribute for this purpose.
You can validate your HTML online here
echo "<td><button onclick='deleteproduct()' class='delete'>Delete</button><input type='hidden' id='productid' vlaue='".$rows["id"]."'></td>";
For your requirement, you can use anchor tag instead of using a form with a hidden input field to reduce the DOM size and call the function on click and pass the function the productId as a parameter.
Here's the code:
<?php
$connect = mysqli_connect("localhost","root","","abu");
if($connect){
$showdata = mysqli_query($connect,"SELECT * FROM dealers");
if(mysqli_num_rows($showdata)>0){
$i = 1;
while($rows = mysqli_fetch_assoc($showdata)){
echo "<tr id='row-".$rows["id"]."'>";
echo "<td>".$i."</td>";
echo "<td>".$rows["dealer_name"]."</td>";
echo "<td><a href='#' onclick='return deleteproduct(".$rows["id"].")'>Delete</a></td>";
echo "</tr>";
$i++;
}
}else {
echo "<center><i>No Dealers to show</i></center>";
}
}
?>
JavaScript:
function deleteproduct( delId ){
var tableRowId = 'row-'+delId;
// you got delId and tableRowId to remove the table row
// do ajax stuff here...
return false;
}
Let me know how it went.
because its "value" and not "vlaue" ;)
input type='hidden' id='productid' vlaue='".$rows["id"]."'
2.
you're iterating over your resultset and printing out an input-field with the id "productid".
In your code, EVERY column has the SAME id. Thats the reason your javascript isn't working as expected. An ID needs to be unique.
You need to send the value (product id) as the function parameters. Do it like this:
<input type="hidden" onclick="deleteproduct(this.value)" value="$yourRowId"/>
or
<input type="hidden" onclick="deleteproduct($yourRowId)" />
and this is how you can retrieve the value in JS:
<script type="text/javascript">
function deleteproduct(id)
{
alert(id); // your product ID
}
</script>

How to get value of checkbox from PHP and DOM

i need to know how on earth to get my checkbox value from PHP that is in a loop and also might be in DOM. I have to put that checkbox inside the loop to make it being shown on each row of databases. I tried to call it back using different method but none success. The last part is javascript but i don't have any clue how to do that.
My code for javascript index.php.
function ajaxSearchUpdater(p){
$("#result").show();
var x = $("#search").val();
var y = $("#edulevel").val();
var pagelim = $("#pagefpe").val();
var pagenumber = p;
var checkb = $(".sBorrow").val()
$.ajax({
type:'POST',
url:'userres.php',
data:'q='+x+'&e='+y+'&pagelim='+pagelim+'&pageno='+pagenumber+'&checkb='+checkb,
cache:false,
success:function(data){
$("#result").html(data)
}
});
}
$(document).ready(function(e) {
ajaxSearchUpdater(1); // fires on document.ready
$("#search").keyup(function() {
ajaxSearchUpdater(1); // your function call
});
$("#edulevel").click(function() {
ajaxSearchUpdater(1); // your function call
});
$("#pagefpe").click(function() {
ajaxSearchUpdater(1); // your function call
});
$('.sBorrow').on('change', function(){
var checkBorrow = $(event.target);
var isChecked = $(checkBorrow).is(':checked');
alert("test");
alert(isChecked);
alert('checkbox'+checkborrow.attr('id')+'is checked:'+isChecked);
});
});
$(document).ready(function() {
$('.sBorrow').on('change', function(event) {
var checkbox = $(event.target);
var isChecked = $(checkbox).is(':checked');
alert('checkbox ' + checkbox.attr('id') + ' is checked: ' + isChecked);
});
});
My code for the checkbox in PHP userres.php
if($stmt->rowCount() > 0){
$r=$stmt->fetchAll();
echo "<table class='tablesorter-blackice' id='myTable' style='width:97%; table-border: 1'>";
echo "<thead>";
echo "<tr>";
echo "<th>No.</th>";
echo "<th>No.Matric</th>";
echo "<th>Name</th>";
echo "<th>Programme</th>";
echo "<th>Title</th>";
echo "<th>Thesis Level</th>";
echo "<th>Serial Number</th>";
echo "<th>Availability</th>";
echo "<th>Select book (Max 3)</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
foreach($r as $row){
$sBorrow = $_SESSION['sBorrow'];
echo "<tr align='center'><td>". ($startrow+1) ."</td><td>". $row['matricno'] ."</td><td>". $row['studentname'] ."</td><td>". $row['programme'] ."</td><td>". $row['title'] ."</td><td>". $row['thesis_level'] ."</td><td>". $row['serialno'] ."</td><td>". $row['bavailable'] ."</td><td>
<form method='post'>
<input type='checkbox' name='sBorrow' id='sBorrow' class='sBorrow' value='". $row['serialno'] ."'>
</form></td></tr>";
$startrow++;
//echo $row['education_level'];
}
echo "</tbody>";
echo "</table>";
I don't know what to do since i'm calling that page from ajax and uhh how should i explain this.
You know index.php -> userres.php -> index.php using ajax.
for javascript on the bottom part is what i have done and i dont think its right. I tried to create one other document ready for this checkbox but still even alert not showing up. I'm confused. please help T_T

Validate PHP variable via Javascript

Im looking to pass one variable from my PHP code to my Javascript code to validate a figure. I'm creating a shopping cart scenario whereby i have a variable 'in_stock' which specifies the amount of stock available for a product. If I enter an amount that is greater than the 'in_stock' available i need an error to be thrown. This is currently what I have:
Java Script
<script language="javascript">
function numCheck()
{
var enteredChar = document.getElementById('add_value').value;
var stockavailable ="<?php echo $stock?>";
//To check if a non-numerical value is entered
if (isNaN(enteredChar))
{
alert("Not a Number!");
return false;
}
//To check if the input is empty
if (enteredChar=="")
{
alert("Empty!");
return false;
}
//To check if the amount entered is not greater than the amount in stock
if (enteredChar > stockavailable)
{
alert("Not enough in stock");
return false;
}
}
</script>
This is all occurring whilst my PHP has called the database and returned the value on the screen. As follows:
PHP
$product_id =(int)$_GET['product_id'];
$username = "potiro";
$password = "pcXZb(kL";
$hostname = "rerun";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("poti",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM products where product_id=$product_id");
echo '<form name="form1">';
echo '<table class="Grocery-table">';
while($row = mysql_fetch_array($result))
{
$stock =$row['in_stock'];
$product_id = $row['product_id'];
echo "<tr><td><b>Product ID</b></td>";
echo "<td>";
echo $product_id;
echo "</td></tr>";
echo "<tr><td><b>Product Name</b></td>";
echo "<td>";
echo $row['product_name'];
echo "</td></tr>";
echo "<tr><td><b>Unit Price</b></td>";
echo "<td>";
echo $stock;
echo "</td></tr>";
echo "<tr><td><b>Unit Quantity</b></td>";
echo "<td>";
echo $row['unit_quantity'];
echo "</td></tr>";
echo "<tr><td><b>In Stock</b></td>";
echo "<td>";
echo $row['in_stock'];
echo "</td></tr>";
echo '<tr><td><b>Add</b></td><td><Input type="text" id="add_value" name="cart"></input></td></tr>';
echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';
}
echo "</table>";
echo "</form>";
mysql_close($dbhandle);
?>
add your stock value to a hidden input value stock_value
echo '<tr><td><b>Add</b></td><td><Input type="text" id="add_value" name="cart" ></input><Input type="hidden" id="stock_value" name="stock_value" value="'.trim($stock).'"></input></td></tr>';
echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';
in javascript
<script language="javascript">
function numCheck()
{
var enteredChar = document.getElementById('add_value').value;
var stockavailable =document.getElementById('stock_value').value;

calling a php function in javascript

I dont know how to use ajax in my problem:
I have a function in php (assign) that update a temporary table in database, I want to when user user click on a button (feedback function that is defined in javascript) this function (assign) run, what should I do?
<script>
function feedback(){
var boxes = document.getElementsByClassName('box');
for(var j = 0; j < boxes.length; j++){
if(boxes[j].checked) {
assign(1);
}
else{
assign(0);
}
}
}
</script>
<?php
$con = mysql_connect("localhost", "root", "")
or die(mysql_error());
if (!$con) {
die('Could not connect to MySQL: ' . mysql_error());
}
mysql_select_db("project", $con)
or die(mysql_error());
$result = mysql_query("select * from words");
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
$idd= $row['id'] ;
echo "<td>". "<div class='hiding' style='display:none'>".$row['meaning']."</div>"."</td>";
echo "<td>";
echo "<input class=\"box\" name=\"$idd\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
function assign($checkparm){
//mysql_query("update words set checking=$checkparm ");
mysql_query("create TEMPORARY TABLE words1user1 as (SELECT * FROM words) ");
mysql_query("update words1user1 set checking=$checkparm ");
}
mysql_close($con);
?>
<button onclick="ShowMeanings()">ShowMeanings</button>
<button onclick="feedback()">sendfeedback</button>
There is only one way to call a php function after the page is loaded:
1.ajax:
function callPHP() {
$.ajax ({
url: "yourPageName.php",
data: { action : assign }, //optional
success: function( result ) {
//do something after you receive the result
}
}
in your PHP, write
if ($_POST["action"] == "assign")
{
assign(your parameters); //You need to put the parameters you want to pass in
//the data field of the ajax call, and use $_POST[]
//to get them
}
There are many great guides on the internet. I will however suggest you get too know JQuery. It will help you on your learning curve.
function ajaxCall(){
$.ajax({
type: "GET",
url: "scripts/on/serverside.php"
});
};

Categories