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

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>

Related

Not able to read/pass JS value to server in PHP

I'm fetching value from Mysql in DropDown. Based on user selection a table should be populated.
But whatever I'm selecting in dropdown, it's not getting sent to server.
Please find below code:
Fetch value in dropdown
<?php
$result = mysqli_query($con, "SELECT name FROM restaurants;");
echo "<select name='sub1' id='resdropdown' onchange = 'showMenu(this.value)'>";
while ($row = mysqli_fetch_array($result)){
echo "<option value='" . $row['name'] ."'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
Script to send value to server
function showMenu(str) {
/* var x = document.getElementById('resdropdown');
str = x.value;
alert(str); */
var ajax = new XMLHttpRequest();
var method = "GET";
var asynchronous = true;
var data = str;
ajax.open(method, "test.php?q="+data, asynchronous);
//sending ajax request
ajax.send();
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("testajaxid").innerHTML = this.responseText;
alert(str);
}
};
}
Get Response from server
$q = $_GET['data'];
$result = mysqli_query($con, "SELECT * FROM items where id = '".$q."'");
while($row = mysqli_fetch_array($result))
{
echo '<tr><td>'.$row["name"].'</td><td>'.$row["price"].'</td>';
echo '<td><div class="input-field col s12"><label for='.$row["id"].' class="">Quantity</label>';
echo '<input id="'.$row["id"].'" name="'.$row['id'].'" type="text" data-error=".errorTxt'.$row["id"].'"><div class="errorTxt'.$row["id"].'"></div></td></tr>';
}
Your $_GET variable should be $_GET['q'] instead of $_GET['data'], because you set the URL to test.php?q=data.
Also, you shouldn't put raw user provided data in SQL queries, use prepared statement instead, because of risks of SQL injection.

update php page using ajax using post requests reload the page?

I am trying to change the content of my php web page using ajax as below
the index.php page has input filed that call a function to executed on the button click but my problem is that the page is reload it
so i want to know what I am doing wrong??
Note that i am using the post requests to keep my data secure as w3schools.com recommended
inexd.php file code below
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Site Title</title>
</head>
<body align="left">
<div>
<h4 align="left">Balance Enquiry</h4>
</div>
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNumInput">
<button type="button" onclick="SendForm()">Search</button>
</div>
</form>
<script>
function SendForm()
{
alert("Hello! SendForm start");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
alert("Hello! going to send ajax");
var x = xmlhttp.open("POST","AccData.php", true);
xmlhttp.send(document.getElementById("AccNum").value); // you want to pass the Value so u need the .value at the end!!!
alert(document.getElementById("AccNum").value);
alert("Hello! SendForm end");
}
</script>
</body>
</html>
The data.php file code below
<?php
alert("Hello! php start processing");
$AccountNumber = $_POST['AccNum'];
$conn = oci_connect('admin', 'admin', 'localhost/JDT', 'AL32UTF8');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
alert("Hello! connected to oracle");
$sqlstr = 'SELECT CUSTOMER_ID,CUST_NAME,PHONE1 FROM customers where CUSTOMER_ID=:AccNum';
$stid = oci_parse($conn, $sqlstr); // creates the statement
oci_bind_by_name($stid, ':AccNum', $AccountNumber); // binds the parameter
oci_execute($stid); // executes the query
echo $AccountNumber;
/**
* THIS WHILE LOOP CREATES ALL OF YOUR HTML (its no good solution to echo data out like this)
*/
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
echo "<tr>";
foreach ($row as $item) {
echo "<td align=center>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid); // releases the statement
oci_close($conn); // closes the conneciton
?>
With the <input type="submit" value="Search"> your sending the form the "old" way to the server not with Ajax!
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNuminput">
<button type="button" onclick="sendForm()">Search</button>
</div>
</form>
<script>
function sendForm(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//Execudted when finished and everything its Okay
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST", "acc_data.php", true);
xmlhttp.send("accNum="+document.getElementById("AccNum").value); // you want to pass the Value so u need the .value at the end!!!
}
</script>
Then in your data.php you do not need any html you just need to process the the data that you received by the ajax post request(Session is also not needed for that) . In the xmlhttp.responseText you are receiving your answer from the server when the request is finished.
<?php
$accountNumber = $_POST['accNum'];// set a good variable name
$conn = oci_connect('admin', 'admin', 'localhost/JDT', 'AL32UTF8'); //setup connection
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR); // throws an error on connection error
}
$sqlstr = 'SELECT CUSTOMER_ID,CUST_NAME,PHONE1 FROM customers where CUSTOMER_ID=:ACCNUM'; // sql stirng
$stid = oci_parse($conn, $sqlstr); // creates the statement
oci_bind_by_name($stid, ':ACCNUM', $accountNumber); // binds the parameter
oci_execute($stid); // executes the query
/**
* THIS WHILE LOOP CREATES ALL OF YOUR HTML (its no good solution to echo data out like this)
*/
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
echo "<tr>";
foreach ($row as $item) {
echo "<td align=center>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid); // releases the statement
oci_close($conn); // closes the conneciton
?>

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

Javascript delete isn't working

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'

Using AJAX with forms created by a PHP loop

When I run this all I get is the vars for the first form in the loop. I assume my problem is the forms are in an array and I have no idea how to get the distinct variables out of that array. I am a newbie. $id is always the same but the $law_id is always unique. I appreciate any help. This is for a game I am making that runs fine when I just post to another page but I would really like to keep it one page that just refreshes an output div. I have a couple loops in the code but I am sure if I get this one I can manage the rest.
This is my php loop that creates the forms:
if ($num_rows > 0){
while($data = mysql_fetch_object($ballots)){
$law_id = $data->id;
$question = $data->question;
$query3 = "SELECT * FROM initiative_records WHERE initiative_id = '". $law_id ."' AND player_id = '". $id ."'";
$new_ballots2 = mysql_query($query3,$link) or die("Unable to select: ".mysql_error());
$num_rows = mysql_num_rows($new_ballots2);
if ($num_rows == "0"){$x++;
?>
<form name="initiative_create" class="form_inline">
<input name="pid" type="hidden" value= "<?php echo $id; ?>">
<input name="gid" type="hidden" value= "<?php echo $law_id; ?>">
<input type="button" id="button" value="<?php echo $question; ?>" onclick='JavaScript:xmlhttpPost1("initiative_info.php")'>
</form><br />
<?php
}
}
my ajax script:
function xmlhttpPost1(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage1(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring1());
}
function getquerystring1() {
var form = document.forms['initiative_create'];
var gid = form.gid.value;
var id = form.pid.value;
qstr = 'pid=' + escape(id) + '&' + 'gid=' + escape(gid); // NOTE: no '?' before querystring
return qstr;
}
function updatepage1(str){
document.getElementById("result").innerHTML = str;
}
You should assign a unique name to each form and pass it to your function. Example:
<form name="initiative_create<?php echo $x; ?>">
...
<input type="button" id="button" value="<?php echo $question; ?>"
onclick='JavaScript:xmlhttpPost1("initiative_info.php", <?php echo $x; ?>)'>
And your functions would be
function xmlhttpPost1(strURL, name_index) {
...
self.xmlHttpReq.send(getquerystring1(name_index));
function getquerystring1(name_index) {
...
var form = document.forms['initiative_create' + name_index];
If I understood correctly and $x variable is a counter. If not, use $i or something.
I think you understand what and why I suggest to change.
The problem lies with this line of code:
var form = document.forms['initiative_create'];
Since you're creating multiple forms with the same name only one of the will work.
I'd really recommend using a library like jQuery to make these kind of tasks easier for yourself. A similar script like above can be written in 4 lines of code:
$('form[name=initiative_create]').submit(function ( event ) {
event.preventDefault();
$('#result').load('initiative_info.php', $(this).serialize());
});

Categories