preventDefault is not working on post request - php

I have some problem when I trying to delete data using form with post method, I did this because many people said using $_GET method is not safe enough. So I try using this method,
I load the data from load.php
<?php
session_start();
require_once('../../classes/Config.php');
require_once('../../classes/Database.php');
require_once('../../classes/Query.php');
require_once '../../classes/ErrorHandler.php';
require_once '../../classes/Validator.php';
require_once '../../classes/Token.php';
$connection = new Database($host, $username, $password, $database);
$main = new Query($connection);
$table = 'karyawan';
$selectData = $main->select($table);
while($fetchData = $selectData->fetch_object()){
$delete = '<form action="" method="post"><input type="hidden" name="id_karyawan" value="'.$fetchData->id_karyawan.'"><input type="hidden" name="token" value="'.$_SESSION['token'].'"><a><button type="submit" class="btn btn-danger btn-xs" id="delete" onclick="deleteData()">delete</button></a></form>';
$button = '<td class="text-center">'.$delete.'</td>';
echo '<tr>
<td class="text-center">'.$fetchData->id_karyawan.'</td>
<td class="text-center">'.$fetchData->nama_karyawan.'</td>
<td class="text-center">'.$fetchData->alamat_karyawan.'</td>
<td class="text-center">'.$fetchData->telepon_karyawan.'</td>
<td class="text-center">'.$fetchData->akses.'</td>
'.$button.'
</tr>';
}
in $delete I set a form with POST method, so I have some forms to delete these datas, here is where my load.php should be loaded,
<div class="table-responsive">
<table class="table table-hover table-bordered table-condensed bg-success">
<thead>
<th class="text-center">ID Karyawan</th>
<th class="text-center">Nama Karyawan</th>
<th class="text-center">Alamat Karyawan</th>
<th class="text-center">Telepon Karyawan</th>
<th class="text-center">Hak Akses</th>
<th class="text-center">Opsi</th>
</thead>
<tbody id="load-data">
</tbody>
<tr>
<td colspan="5"></td>
<td class="text-center"><button class="btn btn-info btn-xs" id="showTambah">Tambah</button></td>
</tr>
</table>
<script type="text/javascript" src="karyawan.js"></script>
and here is my jQuery scripts
load();
deleteData();
function load() {
$('#load-data').load('process/karyawan/load.php');
}
function deleteData(){
$('#delete').click(function(e){
e.preventDefault();
alert('testing');
});
}
when I click delete button function deleteData() didn't work well both of preventDefault() or alert() message.
Can someone give me some advices??

Remove deleteData() from submit button and add class called btn-delete on the button and remove $('#delete').click(function(e){}); event and use $('.btn-delete').on("click",function(e){}); this event. As your content loadind dynamically click event will not work you have to use below code.
$('.btn-delete').on("click",function(e){
e.preventDefault();
alert("test")
});

Related

how to id of button in table using jquery?

<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Name</th>
<th>Subject</th>
<th>Message</th>
</tr>
</thead>
<tbody>
<?php
foreach($fetchContactData as $value)
{
?>
<tr>
<td><?php echo $value['email'] ?></td>
<td><?php echo $value['name']?></td>
<td><?php echo $value['subject'] ?></td>
<td><button type="button" class="btn btn-warning" value="<?php echo $value['message'] ?>">Show</button></td>
<?php
}?>
</tbody>
<tfoot>
<tr>
<th>Email</th>
<th>Name</th>
<th>Subject</th>
<th>Message</th>
</tr>
</tfoot>
</table>
Js code:
<script type="text/javascript">
$(document).ready(function(){
$("#example1 button").click(function(){
var id=$(this).attr('value');
});
});
</script>
here at each row there is unique id to button. so onclick of that button i want that id in jquery. I tried many searches from stackoverflow but its not working so anyone can help me with jquery part with this exact same code
Here is my js now i want that long message so that i could show it in modal class div.
[Violation] Forced reflow while executing JavaScript took 73ms ---> This is the error i got
An "id" is always used to identify something and therefore should be unique. So you have to make it unique in the first place. Something like this should work.
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Name</th>
<th>Subject</th>
<th>Message</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
foreach($fetchContactData as $value)
{
?>
<tr>
<td><?php echo $value['email'] ?></td>
<td><?php echo $value['name']?></td>
<td><?php echo $value['subject'] ?></td>
<td><button type="button" class="btn btn-warning" id="show-<?= $i; ?>" value="<?php echo $value['id'] ?>">Show</button></td>
<?php
$i++;
}?>
</tbody>
<tfoot>
<tr>
<th>Email</th>
<th>Name</th>
<th>Subject</th>
<th>Message</th>
</tr>
</tfoot>
</table>
In this code, there will be the variable "$i" that is set to 0 in the beginning and just appended to the id "show-". Last step of the foreach-loop, this 0 is just counted up by one.
This will generate and id in the format of "show-0", "show-1" (you could set $i to 1 in the beginning to make it start counting from 1). In jQuery, you then could use the "starts with"-selector to select all buttons and set an onclick event on it. (just one example) https://api.jquery.com/attribute-starts-with-selector/
<script>
$( "button[id^='show-']" ).on('click', clickhandler);
</script>
So for every button that has an id starting with "show-" you can make it do the action "clickhandler".
your id=button is into loop, so is not unique.
I advise you do not use id, better you can use something like class and in your js script listen click to this, like:
<td><button type="button" class="btn btn-warning button_msg" value="<?php echo $value['message'] ?>">Show</button></td>
Js (jquery)
$(".button_msg').click(function(){
//Do anything
})

How to get id from php loop in jquery

Hi I'm trying to get the id for each row shown in while loop in my jquery function
Here are the request and view (PHP code)
<div class="container">
<table class="table table-striped">
<div class="table responsive">
<thead class="black white-text">
<tr>
<th>#</th>
<th>Nom et Prénoms</th>
<th>Fonction</th>
<th>Université</th>
<th>Email</th>
<th>Contact</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$result = $connection->query($stmt) ;
if($result->rowCount() > 0)
{
while($row = $result->fetch(PDO::FETCH_BOTH))
{
echo '<tr>
<td scope="row">'.$row["id"].'</td>
<td>'.$row["nom"].'</td>
<td> '.$row["fonction"].'</td>
<td> '.$row["nomU"].'</td>
<td> '.$row["email"].'</td>
<td> '.$row["Contact"].'</td>
<td>' ?>
<button type="button" class="btn btn-success valider">Valider</button> /<button type="button" class="btn btn-danger rejeter">Rejeter</button>
<?php
echo '</td>
<td>'
?>
<input type="hidden" class="the_id" value='<?php echo $row[' id ']; ?>'>
<?php echo '</td>
</tr>';
}
}
else
{
echo "0 results";
}
?>
</tbody>
</div>
</table>
</div>
And I want to show the id of each row when I click on the button "valider" for the line with jquery but it's showing the first id for all the row.
Here is th jquery code
$(document).ready(function(){
$('.valider').click(function(e){
alert($('.the_id').val());
});
});
Almost right. Remember that when accessing by a class name rather than an ID, you will get all of those objects.
So, we need to be more specific. Give this a try:
$('.valider').click(function(e){
var id = $(this).parent().parent().find('td').find('.the_id').val();
alert(id);
});
This takes you from $(this), your button, to its parent <td>, then the parent <tr>, then looks for any classes of .the_id inside the tr, in other words, the specific one you want.
I usually add a custom attribute to the elements, like data-custom-id.
'<button type="button" class="btn btn-success valider" data-custom-id="'.$row["id"].'">Valider</button>'
And then in the calling function I can access the object with this
$('.valider').click(function(e){
alert($(this).attr('data-custom-id'));
});
You need to go up to the parent tr to get the related input so you could use closest() with the $(this) :
$('.valider').click(function(e){
alert( $(this).closest('tr').find('.the_id').val() );
});

Fetch and dispaly through a modal database contents of selected in a datatable row when button is click

I have a datatable which retrieves data from db, i want to be to implement a modal pop up under the row improvement actions so instead displaying the actual improvement actions i want like a symbol under that row so when i click it a modal appears with the improvement actions while all the other data remains the same , i want to implement this using ajax but am quite a novice in ajax please assist.
<table class="table table-hover table-striped table-bordered datatable-basic" >
<thead>
<tr>
<tr class="bg-violet-400" >
<th>ID</th>
<th>Site</th>
<th>Date</th>
<th>SN</th>
<th>Gap identified</th>
<th>Improvement Actions</th>
<th>Timeline</th>
<th>Person responsible</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
$connect = mysqli_connect("localhost", "root", "", "dqa");
$query=mysqli_query($connect,"SELECT * FROM action_plan");
while($row=mysqli_fetch_array($query))
{
?>
<tr>
<td><?php echo $row['id'] ?></td>
<td><?php echo $row['site'] ?></td>
<td><?php echo $row['date'] ?></td>
<td><?php echo $row['sn'] ?></td>
<td><?php echo $row['gap_identified'] ?></td>
<td><?php echo $row['Improvement_Actions'] ?></td>
<td><?php echo $row['timeline'] ?></td>
<td><?php echo $row['person_responsible'] ?></td>
<td><?php if( $row['status'] == 1 )
{
echo ' <button type="button" class="btn bg-grey">Approved</button></span>';
}
elseif( $row['status'] == 0 ) {
echo ' <button type="button" class="btn btn-danger">Active Action</button></span>';
}
elseif( $row['status'] == 2 ) {
echo ' <button type="button" class="btn bg-brown"> Resubmission </button></span>';
}
elseif( $row['status'] == 3 ) {
echo ' <button type="button" class="btn bg-orange">Action Due</button></span>';
}
?></td></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
Without any sample data or example data, I can only speculate at what you are trying to accomplish. Here is an example that I think you may find helpful.
$(function() {
$(".table").DataTable();
$(".table tbody .actions").button({
showLabel: false,
icon: "ui-icon-extlink"
}).click(function(e) {
var self = $(this);
var row = $(this).attr("href").substring(1);
var siteurl = "<?php echo siteurl('improvement');?>";
var form = $("<form>", {
id: "form-" + row
});
form.append($("<input>", {
type: "hidden",
name: "rowid",
value: row
}));
var dialog = $("<div>", {
title: "Improvement Actions - Row " + row
}).append(form).dialog({
modal: true,
create: function(e, ui) {
$.getJSON(siteurl + "/" + row, function(data) {
$('[name="rowid"]', this).val(data.id);
});
},
close: function(e, ui) {
self.data("results", form.serialize());
dialog.dialog("destroy").remove();
}
});
});
});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
<table class="table table-hover table-striped table-bordered datatable-basic">
<thead>
<tr>
<tr class="bg-violet-400">
<th>ID</th>
<th>Site</th>
<th>Date</th>
<th>SN</th>
<th>Gap identified</th>
<th>Improvement Actions</th>
<th>Timeline</th>
<th>Person responsible</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>
1
</td>
<td>
LOC-1
</td>
<td>
04/24/2018
</td>
<td>
1001
</td>
<td>
0.1
</td>
<td>
Improvement Actions
</td>
<td>
</td>
<td>
John Smith
</td>
<td>
<button type="button" class="btn bg-grey">Approved</button>
</td>
</tr>
</tbody>
</table>
Assuming you are using DataTable, The table is populated with various data from PHP, resulting in HTML like shown above. You can then use jQuery UI to program the button to build a dialog. One of the callback events for .dialog() is create, see more: http://api.jqueryui.com/dialog/#event-create
You can perform your AJAX call at this time to get specific data for this dialog. In my example, all of it is being created dynamically, so there is no need to reset forms etc.
I advise using $.getJSON(), but there is nothing wrong with the $.ajax() code you implemented. The $.getJSON() simply assumes you are performing a GET call to a resource that will return JSON data. Resulting in simplified code.
Testing of this example is not complete as the PHP Script URL is fake or will be null.
Hope that helps.

Resized Page - Button submitting and not using jquery

Update, seems it is also happening when i go onto the next page (fullscreen this time).
I'm hoping someone could possible help me as this has been driving me crazy. I have a table full off orders which each row has a button. This button when submitted will show an alert.
I am using data-tables (Responsive), and when the table is all on the screen, the button works as intended. However, when the screen is resized and the button goes within the + icon to expand the row. The button is not running the jquery and is submitting the page.
I have no idea how to fix this and was wondering if there is a workaround. Here is a sample of the code if it helps.
<table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Order Number</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<?php foreach ($orders as $order): ?>
<tr>
<th scope="row">
<?php echo $order['OrderNumber']; ?>
</th>
<td>
<form id="<?php echo $order['OrderNumber']; ?>">
<input type="submit" value="Submit">
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
At the bottom of the page:
<?php foreach ($orders as $order): ?>
<script>
$('#<?php echo $order['OrderNumber']; ?>').on('submit', function () {
alert('Form submitted!');
return false;
});
</script>
<?php endforeach; ?>
Any help would be appreciated! I have no idea why it isn't working when the table is resized.
Use a delegated event handler instead :
$('#datatable-buttons').on('submit', '#<?php echo $order['OrderNumber'];?>', function() {
alert('Form submitted!');
return false;
});
Your event handler does not work because the form not exists in dom at the time of declaration.
But all those dedicated #id based event handlers is completely unnecessary. A single (delegated) handler is sufficient :
$('#datatable-buttons').on('submit', 'form', function () {
alert('Form ' + $(this).attr('id') + ' submitted!');
return false;
});
Hey mate you could try something like this for the alert
<table id="datatable-buttons" class="table table-striped table- bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Order Number</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<?php foreach ($orders as $order): ?>
<tr>
<th scope="row">
<?php echo $order['OrderNumber']; ?>
</th>
<td>
<button type="button" class="btnPress" id="<?php echo $order['OrderNumber']; ?>">Submit</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Bottom
<script>
$('.btnPress').on('click', function () {
alert('Form submitted!');
alert(this.id);
});
</script>

PHP - DataTables Post username from table row for a mysql_query?

I am trying to add a delete button to my DataTables table, but I don't know how I can post the username of the selected row when Delete button is pressed.
Here is how the DataTables is printed:
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Username</th>
<th>Email</th>
<th>Fullname</th>
<th>Class ID</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
while($listDetailsRow = mysql_fetch_array($listDetails)){
?>
<tr>
<td class="success"><?=$listDetailsRow['username']?></td>
<td class="info"><?=$listDetailsRow['email']?></td>
<td class="success"><?=$listDetailsRow['fullname']?></td>
<td class="info"><?=$listDetailsRow['class_id']?></td>
<td>
<form id='delete' action='deleteUser.php' method='post'>
<button type="submit" name="submit" class="btn btn-danger" href="deleteUser.php">
Delete
</button>
</form>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
So it is printed by php until all has been printedm then it stops...
The deleteUsers.php file is as follows:
include('../details.php');
$userDel = $_POST($listDetailsRow['username']);
echo $userDel;
// mysql_query("DELETE * FROM users WHERE username='$userDel'") or die(mysql_error());
I am just trying to get it to print the username from the row of which the delete button was pressed.
Is this possible? Not very good with JS or Ajax so all help is appreciated.
<form id='delete' action='deleteUser.php' method='post'>
<input type='hidden' name='username' value="<?=$listDetailsRow['username'];?>" > <--add this line
<button type="submit" name="submit" class="btn btn-danger" href="deleteUser.php">
Delete
</button>
</form>
php:
$userDel = $_POST['username'];
You can use an a element instead of a form within a button element. See this code:
<tbody>
<?php
while($listDetailsRow = mysql_fetch_array($listDetails)){
?>
<tr>
<td class="success"><?=$listDetailsRow['username']?></td>
<td class="info"><?=$listDetailsRow['email']?></td>
<td class="success"><?=$listDetailsRow['fullname']?></td>
<td class="info"><?=$listDetailsRow['class_id']?></td>
<td>
<!------------- New -------------->
<?php
$params = array( 'username' => $listDetailsRow['username'] );
$href = "deleteUser.php?" . http_build_query($params);
?>
<a class="btn btn-danger" href="<?php echo $href; ?>" > Delete </a>
<!------------- End New -------------->
</td>
</tr>
<?php
}
?>
</tbody>
In deleteUser.php do this:
$userDel = isset($_GET['username']) ? $_GET['username'] : null;

Categories