Confirm action then delete row from mysql table - javascript

I am using javascript to alert user if he is sure to delete row from database.
In html table I am using column for deleting rows.
<td><center><a href="" id="brisi" value="<?=$r['Id']; ?>" class="delete" data-confirm="Are you sure that you want to delete?"><i class="fa fa-times"></i></center>
I am using script to alert user then to navigate to php script to delete row
<script>
var deleteLinks = document.querySelectorAll('.delete');
for (var i = 0; i < deleteLinks.length; i++) {
deleteLinks[i].addEventListener('click', function(event) {
event.preventDefault();
var choice = confirm(this.getAttribute('data-confirm'));
if (choice==true) {
var x =document.getElementById("brisi").value;
$.ajax({ url: 'edit/delete.php?a=1',
type: 'post',
success: function(output) {
document.getElementById("brisi").value = output;
}
});
}
if (choice==false) {
return false;
}
});
}
</script>
Php script
<?php
if ($_GET['a']==1) {
$id = test_input($_POST['brisi']);
echo $id;
}
?>
I am trying to send value of each row. For some reason my js does not work, could anyone provide quick advice?

you should change your html
<td><center><a href="javascript:;" data-value="<?=$r['Id']; ?>" class="delete" data-confirm="Are you sure that you want to delete?"><i class="fa fa-times"></i></center>
and also change javascript
$('.delete').off('click').on('click', function(e){
e.preventDefault();
var choice = confirm($(this).data('confirm'));
if(choice){
var x = $(this).data('value');
$.ajax({
url: 'edit/delete.php?a=' + x,
type: 'post',
success: function(output) {
document.getElementById("brisi").value = output;
}
});
}
else{
return false;
}
});
and php code
<?php
if (isset($_GET['a']) && $_GET['a'] != ''){
$id = test_input($_GET['a']);
echo $id;
}
?>

onclick="return confirm('Are you sure you want to delete this item?');"

I would like to know why you are checking for this:
var x =document.getElementById("brisi").value;
And you don't use it.
I hope also that 'brisi' is the unique ID only for this element.
Next you are doing a POST request with ajax:
$.ajax({ url: 'edit/delete.php?a=1',
type: 'post',
success: function(output) {
document.getElementById("brisi").value = output;
}
});
I notice in your PHP you are trying to GET your posted vriable:
if ($_GET['a']==1) {
$id = test_input($_POST['brisi']);
echo $id;
}
And you should do:
if (isset($_POST['a') && $_POST['a'] == 1) {
$id = test_input($_POST['brisi']);
echo $id;
}
And finally what is this function doing:
test_input($_POST['brisi'])
You don't have any posted value with this index.
To recap If you need more help please post your complete HTML form.

Related

How to do an Ajax request to parse table row column data to PHP on click of table row?

I have a datatable with an numeric value in the first column of the <tr><td> row.
I want to click on that row and parse this value to a PHP page in order to assign this number into a session.
I have below code snippet, but this isn't do the push.
selected is the class of the row when I click on it.
$(".selected td").click(function(parsegroupid) {
var group_id = $(this).attr('data');
$.ajax({
url: "./includes/indexPage/assign_session.php",
type: "post",
data: {
id: group_id
},
success: function(response) {
}
});
});
This is my PHP code:
<?php
ob_start();
if (session_id() == '') {
session_start();
}
$GrpID = $_POST['group_id'];
$_SESSION['grp'] = $GrpID;
ob_end_flush();
?>
Below is a screenshot of the row when selected.
First, you need to check if the ajax call is made.
Based on your previous comments, it seems this is not happening.
You can try to specify the table id in your onclick event:
$("#table_id tbody").on( 'click', 'tr', function (){
var group_id = $(this).find("td:first-child").text();
$.ajax({
url: "./includes/indexPage/assign_session.php",
type: "post",
data: {
id: group_id
},
success: function(response) {
}
});
}
Make the change in your assign_session.php file your have pass the value in id and trying to access value of group_id.
Instead of $_POST['group_id'] use $_POST['id']
change the code like below
<?php
ob_start();
if (session_id() == '') {
session_start();
}
$GrpID = $_POST['id']; // change
$_SESSION['grp'] = $GrpID;
ob_end_flush();
?>
If the ID is in the cell of the and not as an attribute, try this:
var group_id = $(this).html();
Go with this code.
You are posting id and group_id is your value and you added $_POST['group_id'] instead of $_POST['id'].
Hope this will helps you :)
<?php
ob_start();
if (session_id() == '') {
session_start();
}
$GrpID = $_POST['id']; // Change here
$_SESSION['grp'] = $GrpID;
ob_end_flush();
?>

Jquery .onclick POST var using ajax and receiving data from mysql

I'm trying this:
- Onclick on button get this.data-id as id in a DB select
- These data will be dynamically shown in a modal
What I dont know is how to work with ajax, can anyone help?
HTML
<a data-toggle="modal" data-id="'.$method['id'].'" title="Visualizar" class="itemview btn btn-info btn-mini" href="#MethodView">Visualizar</a>
.php
if(!empty($_POST)){
if (isset($_POST['id']) && $_POST['id'] > 0){
$id=$_POST['id'];
GetPaymentMethodView();
}
}
function GetPaymentMethodView() {
global $db;
try{
$query = $db->query("SELECT * FROM payment_methods WHERE id=$id");
$row=$query->fetch(PDO::FETCH_ASSOC);
$result['success'] = true;
$result['result'] = $row;
echo json_encode($result);
return true;
} catch (PDOException $pe) {
return false;
}
}
.js
$('.itemview').click(function (e) {
e.preventDefault();
var uid = $(this).data('id');
$.ajax({
type: "POST",
url: "resources/controllers/get.php",
data: 'id='+uid,
dataType: "json",
success: function (data) {
if (data.success) {
console.log(data.result);
console.log(data.result.id);
} else {
alert("error");
}
}
});
});
In page where you want to display result put something like this
<div class="result"></div>
In try small modification
try{
$query = $db->query("SELECT id, name, bank_info FROM payment_methods WHERE id=$id");
$row=$query->fetch(PDO::FETCH_ASSOC);
$result['success'] = true;
$result['result'] = $row;
echo json_encode($result);
exit;
return true;
}
In js small editing
success: function (data) {
if (data.success) {
//How to show rows in php?
console.log(data.result);
console.log(data.result.id);
var result = data.result;
//prepare markup
var resultHtml = '';
resultHtml += '<p>Id = ' + result.id +'</p>';
resultHtml += '<p>Name = ' + result.name +'</p>';
resultHtml += '<p>Bankinfo = ' + result.bank_info +'</p>';
//Put markup in div
$(".result").html(resultHtml)
} else {
alert("error");
}
}
And see in browser console to understand.
As both code is in same page you can perform this without js/jQuery too, for that just add value of $method['id'] directly to <input>.
See below to understand
Remove value of $method['id'] from <a> tag
<a data-toggle="modal" data-id="" title="Visualizar" class="itemview btn btn-info btn-mini" href="#MethodView">Visualizar</a>
Add value directly to <input> tag
<input type="text" name="methodid" id="methodid" value = "<?php echo $method['id']; ?>" />
And problem solved without js. :) So remove js stuff.

Delete from data base with PHP, Ajax

Hi I am trying to run a delete script that will delete the record from my database using ajax and php. Used without the ajax javascript file the delete_file.php script works fine and is removed from the database.(So I am asssuming the problem lies in the javascript file somewhere.) Once I add the javascript file only it appears to run and delete_file.php does notk. Basically I pass three id's through to delete_file.php find them all in their respective tables then use those variables to find the right file to delete. Any Help is greatly appreciated. I need a fresh pair of eyes, thanks
What I am Clicking
[![enter image description here][1]][1]
html
<?php echo'<li class="col student_file">
<i class="fa fa-times-circle-o"></i>
<a class="the-file student_'.$student_id.'" id="file_'.$file_id.'" href="/application/student/file_management'.$file_path.'" target="_blank"><i class="fa fa-file-archive-o"></i></i></i>'.$file_name.' <span>'.$file_size.'</span></a>
</li>
delete_file_ajax.js
$(document).ready(function() {
"use strict";
$(".delete-file").click(function() {
var container = $(this).parent();
var id = $('.the-file').attr("id");
var string = 'id='+ id ;
if(confirm("Are you sure you want to delete this?")) {
$.ajax({
type: "POST",
url: "delete_file/delete_file.php",
data: string,
cache: false,
success: function(){
container.slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});
delete_file.php
<?php
session_start();
//Connect to Database
require_once('../../../../db_config.php');
$db_connect = connectDB($mysqli) or die(mysqli_error());
//First lets make sure the user is allowed
require_once('../../../../auth/admin_session.php');
//Create our session on session_id
$session_id = $_SESSION['ADMIN_ID'];
//Get the IDs
$s_id = $_GET['student'];
$a_id = $_GET['agent'];
$f_id = $_GET['file'];
//Lets find the Id of the Agency User
$session_query = mysqli_query($db_connect, "SELECT * FROM agency WHERE agency_id = $a_id");
$session_row = mysqli_fetch_assoc($session_query);
$session_num_rows = mysqli_num_rows($session_query);
$agency_id = $session_row['agency_id'];
//Lets find the Id of the Agency User
$student_session_query = mysqli_query($db_connect, "SELECT * FROM students WHERE student_id = $s_id");
$student_session_row = mysqli_fetch_assoc($student_session_query);
$student_session_num_rows = mysqli_num_rows($student_session_query);
$student_id = $student_session_row['student_id'];
//Lets find the Id of the File we want to delete
$file_session_query = mysqli_query($db_connect, "SELECT * FROM uploaded_files WHERE file_id = $f_id AND agency_id = $a_id AND student_id = $s_id");
$file_session_row = mysqli_fetch_assoc($file_session_query);
$file_session_num_rows = mysqli_num_rows($file_session_query);
$file_id = $file_session_row['file_id'];
if(!mysqli_connect_errno()){
$stmt = $db_connect->prepare("DELETE FROM uploaded_files WHERE file_id = ? AND agency_id = ? AND student_id = ?") or die('We Could not locate the file you wish to delete');
$stmt->bind_param('iii', $file_id, $agency_id, $student_id);
$stmt->execute();
$stmt->close();
}
?>
Solution
html
echo '<form class="delete-student-file" action="delete_file/delete_file.php" method="post">';
echo '<li class="col student_file">';
echo '<input type="hidden" name="student-id" value="'.$student_id.'">';
echo '<input type="hidden" name="agency-id" value="'.$agency_id.'">';
echo '<input type="hidden" name="file-id" value="'.$file_id.'">';
echo'<a class="the-file student_'.$student_id.'" id="file_'.$file_id.'" href="/application/student/file_management'.$file_path.'" target="_blank"><i class="fa fa-file-pdf-o"></i>'.$file_name.' <span>'.$file_size.'</span></a>';
echo '<button class="delete-file" name="submit"><i class="fa fa-times-circle-o"></i></button>';
echo'</li>';
echo'</form>';
delete_file.php
//Get the IDs
$s_id = $_POST['student-id'];
$a_id = $_POST['agency-id'];
$f_id = $_POST['file-id'];
delete_file_ajax.js
$(document).ready(function() {
"use strict";
$(".delete-file").click(function(e) {
e.preventDefault();
var container = $(this).parent();
var formData = $('.delete-student-file').serialize();
if(confirm("Are you sure you want to delete this?")) {
$.ajax({
type: "POST",
url: "delete_file/delete_file.php",
data: formData,
cache: false,
beforeSend: function(){
container.animate({'backgroundColor': '#fb6c6c'}, 300);
},
success: function(){
container.slideUp('slow', function() {$(this).remove();});
}
});
}
});
});
It looks like your problem is sending the ajax call as POST and requesting it as GET. Try this:
$.ajax({
type: "GET",
url: "delete_file/delete_file.php",
data: string,
cache: false,
success: function(){
container.slideUp('slow', function() {$(this).remove();});
}
Personally, I would suggest changing your PHP to accept POST rather than GET, but that is just my opinion.
PHP know inside "" is string not variable,but enclose by '' can print variable
I advice you to use '' in sql query.
$session_query = mysqli_query($db_connect, "SELECT * FROM agency WHERE agency_id = '$a_id'");
OR
$session_query = mysqli_query($db_connect, "SELECT * FROM agency WHERE agency_id = '".$a_id."'");

Setting a session variable in PHP using AJAX

After a user clicks a div this javascript function runs:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": "<?php echo $rows['id']?>"},
success:function(data){
window.location.href = 'index.php';
}
});
});
I want to pass in an ID associated with the div the user clicks into my ajax.php file where this code runs:
<?php
session_start();
//connect to db here
$_SESSION['id'] = $_POST['id'];
?>
However this is not working. To expand further what I did to pass get the rows['id'] variable is run this SQL code:
$sql_select = "SELECT id FROM ids WHERE id = '$id'";
$results_select = $conn->query($sql_select);
I then outputted a bunch of divs with id's corresponding to them:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test'></div>";
}
?>
Does anyone know how I can accomplish this?
Use data attributes:
Try:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div data-id='".$rows['id']."' class = 'test'></div>";
}
?>
js:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": $(this).attr('data-id')},//fetch the data attribute
success:function(data){
window.location.href = 'index.php';
}
});
});
Please check your JS code for data: {"id": "<?php echo $rows['id']?>"}. This line may not be able to pass your actual value so store it into div with id attribute and get it by jQuery and pass it.
JS:
$('.test').click(function(e)
{
dataValue = $(this).attr('id');//Get user clicked div id attribute value...
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": dataValue},
success:function(data){
window.location.href = 'index.php';
}
});
});
PHP:
With above JS code you need to make some change for PHP code as well:
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test' id='". $select_rows['id'] ."'></div>";
}
Please confirm this code by print_r($_POST); on AJAX post handler page. This will print the POST data requested by AJAX code.
Let me know if there is any concern regarding this.

Showing Busy loading Indicator during an AJAX Request using jQuery

I have status active/Deactive Buttons when user clicks on active status it turns into deactive with red color and vice versa
currently i'm able to update my status #backend but everytime i should refresh to see my changes!!
my requirement is during active/deactive process of changing status i want to load ajax image loader where loader image should overlay entire screen. and my status should be updated in mysql db!!
please any help is appricated Thanks!
Php Code
<?php
include 'db.php';
$sql = "select * from sections order by id asc";
$data = $con->query($sql);
$str='';
if($data->num_rows>0)
{
while( $row = $data->fetch_array(MYSQLI_ASSOC))
{
$str.="
"?>
<div class="row">
<div class="col-md-1">
<?php
if ($row['status'] == '1')
{
?>
<a href="#" class="btn btn-success btn-sm active" ida='<?php echo $row['id'];?>'></a>
<?php }
else if($row['status'] == '0')
{
?>
<a href="#" class="btn btn-danger btn-sm deactive" idde='<?php echo $row['id'];?>'></a>
<?php } ?>
</div>
</div>
<?php
}
}
else
{
$str .= "<p style='text-align:left;'>No Data Available</p>";
}
echo $str;
?>
Jquery Code
<script type="text/javascript">
$('body').delegate('.active','click',function(e){
var IdStatus = 0;
var id = $(this).attr('ida');
$.ajax({
url:"pages/status1.php",
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
alert('success');
}
});
e.preventDefault();
return false;
});
$('body').delegate('.deactive','click',function(e){
var IdStatus = 1;
var id = $(this).attr('idde');
$.ajax({
url:"pages/status1.php",
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
alert('success');
}
});
e.preventDefault();
return false;
});
</script>
PHP Updation Code
<?php
if(isset($_REQUEST['status']))
{
$status = $_REQUEST['status'];
$id = $_REQUEST['id'];
$sql = 'update sections set status='.$status.' where id='.$id.'';
$result = mysql_query($sql);
if($result)
{
echo 'updated successfully';
}
else
{
echo 'failed to update';
}
}
?>
Try this script with mentioned changes:
Changes:
Keep same attribute as data-id for both the operations
loaderElem will be the loader container which should be there in your DOM
BODY is nothing but a body selector, just to avoid redundant selectors
var elem = $(this); is used as I need this reference after success callback
Also make habit of using error callback as you might need to handle that case
var BODY = $('body');
var loaderElem = $('#loader');
BODY.delegate('.active', 'click', function(e) {
loaderElem.show();
var IdStatus = 0;
var elem = $(this);
var id = elem.attr('data-id');
$.ajax({
url: "pages/status1.php",
data: {
status: IdStatus,
id: id
},
dataType: 'html',
success: function() {
elem.removeClass('active').addClass('deactive');
loaderElem.hide();
alert('success');
}
});
e.preventDefault();
return false;
});
BODY.delegate('.deactive', 'click', function(e) {
loaderElem.show();
var IdStatus = 1;
var elem = $(this);
var id = elem.attr('data-id');
$.ajax({
url: "pages/status1.php",
data: {
status: IdStatus,
id: id
},
dataType: 'html',
success: function() {
elem.removeClass('deactive').addClass('active');
loaderElem.hide();
alert('success');
}
});
e.preventDefault();
return false;
});
Try using beforeSend option of $.ajax()
$('body').delegate('.active','click',function(e){
var IdStatus = 0;
var id = $(this).attr('ida');
$.ajax({
url:"pages/status1.php",
beforeSend: function() {
// do overlay stuff
},
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
// remove overlay stuff
alert('success');
}
});
e.preventDefault();
return false;
});

Categories