I am have a page where i have the table row id defined by 'lesson_id' and i have a delete function for jquery that deletes that row without having to change page.
It is almost all working but when it posts the information to delete_row.php it is not deleting the record.
but delete_row.php is working because i've manually done delete_row.php?id=4 and it deleted that record succesfully.
Any pointers and explanations would be great as i'm still learning.
lessons.php
<table id="lessons" class="table-hover">
<thead>
<tr>
<th>Lesson ID</th>
<th>Lesson Name</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
while($row=mysqli_fetch_array($result)){
echo '<tr id="'. $row['lesson_id'].'">';
echo '<td>'. $row['lesson_id'] .'</td>';
echo '<td>'. $row['name'] .'</td>';
echo '<td><a class="delete">Delete</a></td>';
echo '</tr>';
}
?>
</tbody>
<div id="error"></div>
<script>
$(document).ready(function()
{
$('table#lessons td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
//$('#error').html(data);
$.ajax(
{
type: "POST",
url: "delete_row.php",
data: data,
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
});
</script>
delete_row.php
<?php
include ('../../../config.php');
$con = mysqli_connect ($dbhost,$dbuser,$dbpass,$dbname);
if (!$con){
die('could not connect: '. mysqli_error($con));
}
$error = "";
$success = "";
if($_GET['id'])
{
$id = $_GET['id'];
mysqli_query($con,"DELETE FROM module_lessons WHERE lesson_id='$id'");
}
?>
as its obvious ... this has no sql injection protection on it.
Change $_GET['id']; to $_POST['id'];
Here, you're doing a POST request:
type: "POST",
url: "delete_row.php",
... but in your PHP script you're checking for GET.
Also, as marc b noted, you're currently vulnerable to SQL injection. Look into using mysqli_real_escape_string, or bind_param.
Related
I'm trying fill the table with fetched data from database by the id of selected option. Table content must change when user selects other option. Chosen plugin is working fine and select options is filled with correct values, how to give var selektas from test.php to loader.php in query where kliento_id = $idofclient?
Somehow make selektas == $idofclient so that i could use this variable in query in loader.php
My test.php:
<script type="text/javascript">
$(document).ready(function () {
$('.chosen-select').chosen();
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#.pavadinimai").on("change",function(){
var selektas = $(this).val().split('|');
$.ajax({
type: "POST",
url: "loader.php",
data: {selektas[o]},
success: function(result){
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});
</script>
<select class="chosen-select" name="pavname" id="pavadinimai">
<option selected="selected" value = "">---Pasirinkti---</option>
<?php
echo "Pasirinkite klienta";
$sql = "SELECT id, kliento_pav FROM klientai";
$stmt = mysqli_query($link, $sql);
while ($row = mysqli_fetch_assoc($stmt)) {
echo "<option value='" . $row['id'] .'|'. $row['kliento_pav'] . "'>" . $row['kliento_pav'] . "</option>";
}
list($idofclient,$pavofclient) = explode ('|',$_POST['pavname']);
?>
</select>
<div id="show">
</div>
And this is my code in loader.php
<?php
require_once "config.php";
if(isset($_POST["pavadinimas"])){
$sql_query="SELECT uzsakymai.id, kliento_id, uzsakymai.kiekis,prekes.pavadinimas,uzsakymai.aprasymas FROM uzsakymai INNER JOIN prekes ON uzsakymai.prekes_id = prekes.id INNER JOIN klientai on uzsakymai.kliento_id = klientai.id WHERE kliento_id = $idofclient"
$resultset = mysqli_query($link, $sql_query) or die("database error:". mysqli_error($link));
while( $result = mysqli_fetch_assoc($resultset) ) {
?>
<br>
<table id="data_table" class="table table-striped">
<thead>
<tr>
<th>Prekės pavadinimas</th>
<th>Kiekis</th>
<th>Aprašymas</th>
</tr>
</thead>
<tbody>
<tr id="<?php echo $result ['id']; ?>">
<td><?php echo $result ['pavadinimas']; ?></td>
<td><?php echo $result ['kiekis']; ?></td>
<td><?php echo $result ['aprasymas']; ?></td>
</tr>
</tbody>
</table>
<?php } ?>
<?php
echo $result
}
?>
I'm using ...jquery/3.1.1/jquery.min.js
Try this
Initially you initialized the table so first clear that table
$('#myTable').dataTable().fnDestroy();
Then initialize again after ajax success
$('#myTable').dataTable();
Like this.....
$(document).ready(function(){
$("#.pavadinimai").on("change",function(){
$.ajax({
type: "POST",
url: "loader.php",
data: {$idofclient},
success: function(result){
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});
$(document).ready(function() {
$("#pavadinimai").on("change", function() {
var pavadinimai = $("#pavadinimai").val();
$.ajax({
type: "POST",
url: "loader.php",
data: {
pavadinimai: pavadinimai
},
success: function(result) {
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});
I want to delete row in database without reloading the page. I have written following codes. It does delete row in page but not in database. which means connection not going to ajax. pls help.
<?php
$advances_result= mysqli_query($conn, "SELECT * FROM advances") or die("error");
?>
<table border>
<caption>ADVANCES</caption>
<tr>
<th>Date</th>
<th>EmpName</th>
<th>EmpCode</th>
<th>Amount</th>
<th>Comment</th>
<th>Action</th>
</tr>
<?php
while($row = mysqli_fetch_array($advances_result)){
?>
<tr>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['empname'];?></td>
<td><?php echo $row['empcode'];?></td>
<td style='text-align:right'><?php echo $row['amount'];?></td>
<td><?php echo $row['comment'];?></td>
<td><button class="delete" id="<?php echo $row['id']; ?>" > Delete</button></td>
</tr>
<?php
}
?>
</table>
'jquery part'
<script>
$(document).ready(function(){
$(".delete").click(function() {
if (confirm("Do you want to delete this row?"))
{
var row = $(this).parents('tr');
var id = row.attr("id");
var data = 'id=' + id ;
$.post({
type: "post",
url: "deleteadvances.php",
data: data,
cache: false,
success: function(){
row.slideUp('slow', function() {$(row).remove();});
}
});
}
return false;
});
});
</script>
'deleteadvances.php' page:
<?php
include("connection.php");
$id = $_POST['id'];
mysqli_query($conn,"INSERT INTO advancehistory SELECT * FROM advances WHERE ID='".$id."'");
mysqli_query($conn,"DELETE FROM advances WHERE ID='".$id."'");
?>
You need to test the output of mysqli_query in deleteadvances.php, if all good, it shows JSON Ok message that is easy parsable with $.post on the jQuery side.
e.g: {"deleted":"id"} on success or {"error":404} on error not found.
I think the id that you're passing from javascript to ajax is incorrect.
var data = 'id=' + id;
is appending the id with string 'id=' and now it finally becomes a string. When it is being passed to ajax, there is just a value and not a [key, value] pair. So, when you are accessing it in php you will get wrong id or Null value.
Try:
$.post({
type: "post",
url: "deleteadvances.php",
datatype : 'json',
data: {
id : id
},
cache: false,
contentType : 'application/x-www-form-urlencoded; charset=utf-8'
});
Change 'deleteadvances.php' page:
<?php
include ('connection.php');
$id=$_POST['id'];
$delete = "DELETE FROM table_name WHERE id=$id";
$result = mysqli_query($db,$delete) or die("Bad SQL: $delete");
?>
I am using the following PHP code to delete my data from a mysql database. It's working for me, but it's redirecting me another page named delete_ac.php. I want to keep it in the same page (index.php), and if possible I want to use jquery so that data is deleted without redirecting the page.
index.php
<?php
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
?>
<tr>
<td bgcolor="#FFFFFF" style="border:1px solid black" >
<?php echo $row[0].' '; ?>
</td>
<td bgcolor="#FFFFFF" style="border:1px solid black">
<?php echo $row[1]; ?>
</td>
<td bgcolor="#FFFFFF">
delete
</td>
</tr>
<?php
}
?>
<?php include 'footer.php'; ?>
delete.ac.php
<?php
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("dbname");
$tbl_name="tablename"; // Table name
// get value of id that sent from address bar
$id=$_GET['id'];
// Delete data in mysql from row that has this id
$sql="DELETE FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
// if successfully deleted
if($result){
echo "Deleted Successfully";
echo "<BR>";
echo "<a href='index.php'>Back to main page</a>";
}
else {
echo 'Error';
}
?>
<?php
// close connection
mysql_close();
?>
A simple answer for you would be:
Include a delete class in your anchor.
<td bgcolor="#FFFFFF"><a class="delete" href="delete_ac.php?id=<?php echo $row[0]; ?>">delete</a></td>
Bind its click to jquery
$('a.delete').on('click', function(e){
var href = $(this).attr('href');
$.ajax({
'url' : href,
'type' : 'GET',
'success' : function(data) {
alert('Data: '+data);
},
'error' : function(request,error)
{
alert("Error");
}
});
});
As others have mentioned, look into SQL prepared statements.
To answer your question, you'd use the following for the ajax call
$.ajax({
method: "POST",
url: "delete.ac.php",
data: { id: PUT_YOUR_ID_VALUE}
});
and change $id=$_GET['id']; to $id=$_POST['id']; in delete.ac.php
Here's a new index.php that uses PDO and removes the need for a second, separate page. It's not perfect, and there's some stuff that can still be cleaned, but this is how I'd change it (while trying to keep it as close as possible to your posted code)
<?php
//Run the following code if and only if a POST
//request is made to this page.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("dbname");
//This is really important. This is a predefined statement
//the code you had is at risk for SQL injection. Please read up on this
$sql = "DELETE FROM :TABLENAME WHERE id = :ID";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':ID', $_POST['id']);
$stmt->bindParam(':TABLENAME', "tablename"); //put tablename here
$stmt->execute();
}
// This ends the 'POST' code
//
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
?>
<tr>
<td bgcolor="#FFFFFF" style="border:1px solid black" >
<?php echo $row[0].' '; ?>
</td>
<td bgcolor="#FFFFFF" style="border:1px solid black">
<?php echo $row[1]; ?>
</td>
<td bgcolor="#FFFFFF">
delete
</td>
</tr>
<?php
}
?>
<script>
//We're creating a javascript function that will be called
//when the user clicks 'delete'. It takes the ID and passes it
//in the AJAX call
function delete(id){
$.ajax({
method: "POST",
url: "index.php",
data: { id: id}
});
}
</script>
<?php include 'footer.php'; ?>
There is a div element :
...
<div id="liste_secteurs"></div>
...
<script type="text/javascript">
$(document).ready(function() {
rechercheSecteursEtProduits(0); // setting the div's content
$('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
});
});
function rechercheSecteursEtProduits(pn){
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_user="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html); // this is the div element
}
</script>
Code of ListerProduitsUserParSecteursAjax.php :
<?php
... // getting database data
?>
<p>Total : <?php echo $nr; ?></p>
<div><img src="<?php echo HTTP_ICON.'plus.png'; ?>" /></div>
<?php echo $paginationDisplay; ?>
<table id="table" class="data display " >
<thead style="background-color:#CCC">
<tr>
<th><?php echo _getText("service.produit.form.secteur_activite");?></th>
<th><?php echo _getText("service.produit.form.titre");?></th>
<th></th>
<th><?php if($data["secteur"]["cnt"] > 0){ ?><input type="checkbox" id="check_all"><?php }?></th>
</tr>
</thead>
<tbody style="background-color:#FFF">
<?php
if($data["secteur"]["cnt"] > 0){
for($i=0;$i<$data["secteur"]["cnt"];$i++){?>
<tr class="odd gradeX">
<td><?php echo $data["secteur"][$i]["secta_lib_fr"] ?></td>
<td><?php echo $data["secteur"][$i]["produit_lib"] ?></td>
<td align="center" style="vertical-align:middle"><img src="<?php echo HTTP_ICON.'edit.png'; ?>" alt="<?php echo _getText('main.btn.modifier'); ?>" style="height:10px;width:10px;" /></td>
<td align="center" style="vertical-align:middle"><input type="checkbox" id="prod_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_produit']; ?>"><input type="hidden" id="secteur_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_secteur']; ?>"></td>
</tr>
<?php } ?>
<?php
}
else{
?>
<tr class="odd gradeX">
<td colspan="4" align="center"><b><?php echo _getText('main.liste.no_data'); ?></b></td>
</tr>
<?php }?>
</tbody>
</table>
<?php if($data["secteur"]["cnt"] > 0){ ?>
<div align="right"><input name="btnSupprimer" id="btnSupprimer" type="button" value="<?php echo _getText("main.btn.delete"); ?>" class="btn btn-blue"/></div>
<?php } ?>
<?php echo $paginationDisplay; ?>
When the page loads for the first time then the delete button works fine : the selected rows are deleted , and the list reappears accordingly to new database data. But later when I want to delete other rows then the alert does not show when I check some checkboxes and clicking the delete button !
So what is wrong in my approach ?
From what I am reading you are having problems with the row that are added from the database.
What could be the problem is when you execute this peace of code:
$('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
When you call the $.click() function you add a event to all the existing DOM object that have a id of 'btnSupprimer', however this doesn't update if you add a new DOM object. So what you should do is call this function every time you add a new row. you would get something like this:
function rechercheSecteursEtProduits(pn){
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_user="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html);
$('#btnSupprimer').click(addClickHandler()); // this is the div element
}
function addClickHandler(){
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
}
I hope it helps
Try using on instead of click as below
$('#btnSupprimer').on("click","#liste_secteurs",function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
});
Use the dynamic jquery selector instead of the regular 'click' event
$('#liste_secteurs').on('click', '#btnSupprimer', function() {});
// $("container").on("event", "button", function() {});
As from Caveman's answer I made some updates :
function rechercheSecteursEtProduits(pn) {
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_usermer="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html);
$('#btnSupprimer').on('click',function(){
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
if (confirm("Do you want to remove these records ?")) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0);
}
}
});
}
And it works !
I'm using bootstrap modal and currently i'm stuck with displaying the values to modal.
here is the html when the user will click view
<a data-toggle="modal" data-id="<?php echo $row33['bicycle_id']; ?>" href="#myModal" class="Buto" >view</a>
then i used jquery-ajax to pass the value of data-id to execute a query in php
$(document).on("click",".Buto", function () {
var dataID = $(this).data('id');
$.ajax({
url: 'getId.php?id=' + dataID,
type:'GET',
dataType: 'json',
context: this,
success: function(values)
{
values = $.parseJSON(values);
$('.table-responsive #pname').html(values.name);
$('.table-responsive #pprice').html(values.price);
$('.table-responsive #pdescription').html(values.description);
}
});
});
here is the getId.php file
<?php
include 'includes/connection.php';
$modalDataId = $_GET['id'];
$resu = mysqli_query($conn,"SELECT * FROM bicycle WHERE bicycle_id = $modalDataId");
while ($row7 = mysqli_fetch_assoc($resu)){
$values['name'] = $row7['name'];
$values['price'] = $row7['price'];
$values['description'] = $row7['description'];
}
echo json_encode($values);
?>
then the modal where the values should be displayed
<div class="modal-body">
<div class="table-responsive" id = "div1" style = " width: 100%; margin-right: 10%; background-color: white;">
<table id = "" align = "center" class="table table-hover table-striped demo2" style = "table-layout:fixed;"> <thead style = "">
<tr style = "background-color: #428bca; color: white;">
<th class="col-sm-3">BIKE NAME</th>
<th class="col-sm-3" >SRP</th>
<th class="col-sm-3" >DETAILS</th>
</tr>
</thead>
<tbody id="myTable">
<tr style = "text-align: center;" data-toggle="modal" data-id="" data-target="#orderModal">
<td id="pname"></td>
<td id="pprice"></td>
<td id="pdescription"></td>
</tr>
</tbody>
</table>
</div>
</div>
Ok. Let me break your problem up for you:
The first question you should ask is: Is my ajax-success-callback function being called? And how can you verify that your code is executed? Simple: create some output to debug your code. For logging simple variables an alert(...) should be fine. If you want to debug the content of an array you are much better off if you log it to the console.
So what I would try is:
$.ajax({
url: 'getId.php?id=' + dataID,
type:'GET',
dataType: 'json',
context: this,
success: function(values)
{
// not sure about alerts in ajax callbacks but you can try it:
alert('inside success callback');
values = $.parseJSON(values);
// alert a value:
alert('values.name is: '+values.name);
$('.table-responsive #pname').html(values.name);
$('.table-responsive #pprice').html(values.price);
$('.table-responsive #pdescription').html(values.description);
// log all values to the javascript console in your browser
console.log(values);
}
});
Try that and look at the output.
a. You don't see any alert window. This means your success callback function is never executed or you have an javascript error. Look at your javascript console in your browser to see if console.log(values) created an output. More about console.log(...) here: What is console.log and how do I use it?
b. You get to see alert windows. But the second alert goes something like: 'values.name is undefined'. --> Your php is not working as expected.
Without being able to actually debug your code this is how I would improve it:
<?php
include 'includes/connection.php';
$modalDataId = $_GET['id'];
$resu = mysqli_query($conn,"SELECT * FROM bicycle WHERE bicycle_id = $modalDataId");
// You expect one row to be returned then you need no while loop:
$row7 = mysqli_fetch_assoc($resu);
// Initialize values array
$values = array();
if ($row7) {
$values['name'] = $row7['name'];
$values['price'] = $row7['price'];
$values['description'] = $row7['description'];
}
echo json_encode($values);
?>
Try that and come back with your results.
here is the answer thanks to walfish3d. i revised the code he provided.
The jquery-ajax:
$(".Buto").on("click",function () {
var dataID = $(this).data('id');
$.ajax({
url: 'getId.php?id=' + dataID,
type:'GET',
dataType: 'json',
context: this,
success: function(values)
{
$('.table-responsive #pname').html(values.name);
$('.table-responsive #pprice').html(values.price);
$('.table-responsive #pdescription').html(values.description);
// log all values to the javascript console in your browser
console.log(values);
}
});
});
getId.php file:
<?php
include 'includes/connection.php';
$modalDataId = $_GET['id'];
$resu = mysqli_query($conn,"SELECT * FROM bicycle WHERE bicycle_id = $modalDataId");
// You expect one row to be returned then you need no while loop:
$row7 = mysqli_fetch_assoc($resu);
// Initialize values array
$values = array();
if ($row7) {
$values['name'] = $row7['name'];
$values['price'] = $row7['price'];
$values['description'] = $row7['description'];
}
echo json_encode($values);
?>