I'm pulling an array of objects from my database and iterating through them using PHP to display a table. Each result row of the table has the option of deleting that particular record from the database. Each row is also an object, and the object type has a method that will delete itself from the database.
The problem I'm having is thinking through how to get this to work in the view. Right now if you click the delete button, it sets a POST variable to "delete" and reloads the same page wherein a listener process detects the variable and initiates the delete via a hidden input that contains the records database id.
This is all well and good, but these are all objects. Shouldn't each object be able to access it's own methods? It seems the only barrier to this is the interplay between PHP script and HTML forms. My code is below. Ideally, when the delete button is pressed, that particular instance of the object teamleader can run its method teamleader->delete_team_leader().
<?php foreach($teamleaders as $teamleader) { ?>
<tr>
<td><?php echo $teamleader->first_name; ?></td>
<td><?php echo $teamleader->last_name; ?></td>
<td><img src="<?php echo '../img/' . $teamleader->photo;?>" alt="" class="img-fluid tiny-tl-img"></td>
<td><?php echo nl2br(substr($teamleader->bio, 0, 100));?>...</td>
<td><?php echo $teamleader->url_name;?></td>
<form action="index.php?a=edittl" method="post">
<td>
<input type="hidden" name="id" value="<?php echo $teamleader->id?>">
<input type="submit" class="btn btn-default" name="edit" value="Edit">
</td>
</form>
<form action="index.php" method="post">
<td>
<input type="hidden" value="<?php echo $teamleader->id?>" name="id">
<input type="submit" class="btn btn-danger" name="delete" value="Delete" onclick="return confirm('Are you sure you want to delete this team leader?')">
</td>
</form>
</tr>
<?php } ?>
In your case, the best solution I think you can use ajax/jQuery for editing or deleting action.
You don't need to use many forms as now.
The code in front-end like this:
<head>
<script src="jquery.min.js"></script>
</head>
...
<?php foreach($teamleaders as $teamleader) { ?>
...
<td><?php echo $teamleader->url_name;?></td>
<td>
<input type="submit" class="btn btn-default btn-edit" name="edit" value="Edit" data-teamleaderid="<?php echo $teamleader->id?>">
</td>
<td>
<input type="submit" class="btn btn-danger btn-delete" name="delete" value="Delete" data-teamleaderid="<?php echo $teamleader->id?>">
</td>
</tr>
<?php } ?>
And the code with using ajax/jQuery is:
$(document).ready(function(){
$('.btn-delete').on('click',function(){
var _this = $(this);
var _teamleaderid = $(this).data('teamleaderid');
if (!confirm('Are you sure you want to delete this team leader?')) return false;
$.ajax(
url:'delete.php',
type:'post',
data: {
teamleaderid: _teamleaderid
},
dataType:'json',
success:function(data) {
if (data.return) {
$(_this).parent().parent().remove();/*Remove the current row in table html*/
alert('This teamleader has been deleted');
}
}
);
});
});
The delete.php code in backend is:
<?php
... #connect database
$teamleader_id = filter_input(INPUT_POST,'teamleader');
$check_delete = $dbconn->query("DELETE from teamleader_table WHERE id={$teamleader_id}");
print json_encode('return'=>$check_delete);
die();
?>
Related
I have a button inside a table row which changes with a boolean value.
<tr id="<?php echo $zeile['id'] ?>" value="<?php echo $zeile['id'] ?>" class="task">
<td >
<form method="POST" action="main.php" value="<?php echo $zeile['id']; ?>">
<?php if ($done == true): ?>
button type="submit" name="checkbtn" id='<?php echo $zeile['id']; ?>' >
Check
</button>
<input type="hidden" name="id" value="<?php echo $zeile['id']; ?>">
<?php else: ?>
<button type="submit" name="uncheckbtn" id='<?php echo $zeile['id']; ?>'>
UnCheck
</button>
<input type="hidden" name="id" value="<?php echo $zeile['id']; ?>">
<?php endif ?>
</form>
</td>
The boolean value is change after the button is clicked here for ('checkbtn' and 'uncheckbtn')
$done = true;
if(isset($_POST['checkbtn'])){
*sqlvariables*
$done = false;
*sql*
}
with my jquery I want that I can click anywhere on the row to do a button click:
$(".table tr").on('click', function() {
$(this).toggleClass('highlighttask');
$(this).find('button[name="checkbtn"]').click();
});
The Problem is that every button changes to unchecked if I click on one row.
I think that I need to work with id's, but I don't know how.
You already have click event handler on tr so no need to use closest, just use find button
$(".table tr").on('click', function() {
$(this).toggleClass('highlighttask');
$(this).find('button[name="checkbtn"]').click();
});
A form is dynamically created with PHP loop and presents one row from DB. I'm asking a user for input through prompt when he changes qty, but when I send it with AJAX to PHP it's empty. I guess it's because hidden input "new_message" is filled at the same time AJAX is sending values to PHP script so at that moment is blank. For the first row generated I get a message, but not for any other row.
Can you help me how to pass prompt input to PHP script?
//Update qty on article
$('.update_qty').on('change', function() {
var message = prompt("Upišite razlog za izmjenu količine:");
//e.preventDefault();
//Get message value
$('#new_message').val(message);
var data = $('#form1').serializeArray();
if (message != "" || message != NULL) {
$.ajax({
type: 'POST',
url: 'update_qty.php',
data: data,
success: function(data) {
alert(data);
}
});
} else {
alert("Empty");
e.PreventDefault();
return false;
}
});
<tbody>
<?php if (!empty($sales_plan_list)) {
foreach($sales_plan_list as $sales_key => $sales_value) {
?>
<tr class="new">
<td>
<a href="view_product_sales.php?id=<?php echo $sales_value['article_id']; ?>">
<?php echo $sales_value['article_no']; ?>
</a>
</td>
<td><?php echo $sales_value['description']; ?></td>
<td><?php echo myNumberFormat($sales_value['rrp']); ?></td>
<td>
<form name="form1" id="form1" method="POST" action="update_qty.php">
<input type="text" name="update_qty" class="update_qty" id="qty" value="<?php echo $sales_value['qty'] ?>"><?php echo ' Kom'; ?>
<input type="hidden" name="article_id" id="article_id" value="<?php echo $sales_value['article_id']; ?>">
<input type="hidden" name="sales_plan_id" id="sales_plan_id" value="<?php echo $sales_plan_id; ?>">
<input type="hidden" name="product_mix_id" id="product_mix_id" value="<?php echo $product_mix_id; ?>">
<input type="hidden" name="new_message" id="new_message" value="">
</form>
</td>
<td>
</td>
</tr>
<?php
}
}
?>
</tbody>
The problem is that you have multiple elements with the same id. You should NOT do that. You check the value in jQuery and then send different form data.
This is all just quessing, I am unable to check it. But try changing id to class and make sure that you send the right form data.
For example change this
<form name="form1" id="form1" method="POST" action="update_qty.php">
to this
<form name="form1" id="form<?= $sales_key; ?>" method="POST" action="update_qty.php">
I can't get the value of the check box field. This is the structure of my code
<form action="<?php echo base_url()?>Home/dashboard" method="post">
<button class="btn btn-default" type="submit" name="delete" onclick="cliked1(event)"
style="margin-left:2px;background-color:blue;color:white;">Delete Item</button>
<td><input class="checkbox" type="checkbox"name="cb" value="1"> 1 </td>
</form>
In the controller
else if(isset($_POST['delete'])) {
$cb = $this->input->post('cb');
echo $cb;
}
I recreated the process it in other file and it works
<form action ="<?php echo base_url()?>Shop/test" method="POST">
<button class='btn btn-danger btn-xs' type="submit" name="delete" value="delete"><span class="fa fa-times"></span> delete</button>
<input type="checkbox" name="cb[]" value="lol">
<br>
<input type="checkbox" name="cb[]" value="yeaa">
</form>
In the Controller
function test()
{
$this->load->view('test');
if(isset($_POST['delete']))
{
$id = implode('^',$this->input->post('cb'));
print_r($id);
}
}
And I apply this process and it turns like this
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<th>ID</th>
<th>Item Photo</th>
<th>Item Name</th>
<th>Stocks</th>
<th>Date Posted</th>
<th>Price</th>
<th>Actions</th>
</thead>
<tbody>
<form action ="<?php echo base_url()?>Shop/test" method="POST">
<?php
$x=1;
foreach($shop_items as $key)
{
?>
<tr>
<td><input class="checkbox" type="checkbox" name="cb[]" value="<?php $key->shop_item_id?>"> <?php echo $x;?> </td>
<td><center><img src="<?php echo base_url()?>uploads/items_main/<?php echo $key->shop_item_main_pic;?>" style = "width:60px;height:50px;"alt=""></center></td>
<td><?php echo mb_strimwidth($key->shop_item_name, 0, 18,"...");?></td>
<td style="width:10px;"><center><button><span class="fa fa-eye"></span></button></center></td>
<td><?php echo date('F,d,Y',strtotime($key->shop_item_date_posted))?></td>
<td><?php if(!$key->shop_item_sale){ echo number_format($key->shop_item_orig_price);}
else{ echo "<font color='red'>".number_format(intval($key->shop_item_orig_price-($key->shop_item_orig_price*($key->shop_item_sale/100))))."</font> ";}?></td>
<td>
Bid | View
</td>
</tr>
<?php
$x+=1;
}
?>
<button class='btn btn-danger btn-xs' type="submit" name="delete" value="delete"><span class="fa fa-times"></span> delete</button>
</form>
</tbody>
</table>
The problem is that the submit button does not work.
In case of a checkbox, when the checkbox is not checked, you will not get the checkbox set in the $_POST. So to get the value of checkbox, you need to do this:
if (isset($_POST["cb"])) {
// Checkbox is checked.
$cb = $_POST["cb"];
} else {
// Checkbox is not checked.
}
And please do not check on type="submit".
From one of the resources:
In most cases this will work, but there are a few occasions when it won't. To identify when this condition will fail we have to look at the different ways of submitting a form.
There are two ways of submitting a form, one is to click the submit button, the other is to hit return, of which will invoke the submit button. The problem occurs when you hit the return button (as most people do), when using Internet Explorer (the most commonly used browser) and when the submit button does not have focus. This will submit the form, but it will not send the submit variable, which would mean the script we are using above will fail.
I fetch SQL data with a while loop and insert the data into a table. With a form and a submit button i can save modified values.
My simplified code:
<table>
<tr>
<?php
//SQL QUERY
//...
while ($row = mysql_fetch_array($sql_header)) {
$var_ab = $row['ab'];
$var_id = $row['id'];
?>
<form id="form1" action="" method="POST">
<td>
<input type="text" value="<?php echo $var_ab; ?>"
</td>
<td>
<input type="text" value="<?php echo $var_id; ?>"
</td>
//PLACEHOLDER FOR SECOND FORM
<?php
}
?>
</tr>
<td>
<input type="submit" name="save" value="SAVE" class="classsubmit" />
</td>
</form>
</tr>
</table>
So far, so good. So, how can I insert a second form to delete an entry? I've tried to place this code (PLACEHOLDER FOR SECOND FORM - see above)
<td>
<form id="form2" action="" method="POST">
<input type="text" value="<?php echo $var_id;?>"
</form>
</td>
but it's not working and it's not allowed to nest forms.
Any suggestions?
If you only want to delete an entry on the page or in the database you could try a button or a span with an onclick function.
for example:
<span onclick="window.location='?delete=<?php echo $row[(unique-value-in-database-from-this-row)]; ?>'; return false">Delete entry</span>
Make sure you add return false or the first form will be submitted. If you use a button make sure it has type="button"
On this page could be a PHP code like this:
if(isset($_GET['delete']))
{
$item = $_GET['delete'];
//SQL connect
$result = mysql_query($conection ,"DELETE FROM table WHERE uniquevalue='$item'");
}
I hope gives an idea for a solution.
I'm wondering which is the best way to map <a href=...></a> hyperlinks performing a HTTP GET to perform a HTTP POST (I'd like to avoid passing all variables in the URL)? For instance, the 2 hrefs below. Furthermore, I would like also to get rid of the submit button and use a regular <a href=...></a> hyperlink. Any suggestions?
<form action="test.php?action=update" method="post" id="cart">
<table>
<tr>
<td>
<a href="test.php?action=delete&id=<?php echo $id ?>" class="r">
remove
</a>
</td>
<td>
add
</td>
</tr>
<tr>
...
</tr>
</table>
<div> <button type="submit">Update</button> </div>
</form>
I'd suggest using jQuery.post and click. When the link is clicked, submit the data via something like this
$('.r').on('click', function() {
$.post('test.php', {key:'value', key2:'value2'}, function(data) {
//error check here
});
return false;
});
As far as i know you can't perform any POST requests with links. You can make your GET requests with links and php as a fallback for users with javascript disabled and for those who have javascript enabled cancel default behavior for links with javascript and make with ajax your POST request with help of AJAX.
for example:
<a class="submit" href="hallo.html?hello=world&test=yes">Test</a>
and js(i used jquery) would be:
$('.submit').click(function(){
var urlPairs = this.href.split('?')[1].split('&'),
total = urlPairs.length,
current = [],
data = {};
for(;total;) {
current = urlPairs[--total].split('=');
data[current[0]] = current[1];
}
$.post('test.php', data);
return false;
});
you could also write your POST function other for more info check jQuery post function doc
P.S. I wounder, if you are using FORM any way why wouldn't you use submit button, is it because of CSS styling? You could style it the same way like any other element(with some tweaks in some browsers).
You can keep the input tags as hidden in your form to submit them as POST.
<td>remove</td>
<td>add</td>
Rewrite the above using two forms, having <input type="hidden" name="id />
and buttons <input type="button" name="delete" />
etc..
if you run print_r($_POST) in your action script. You'll get a list of the buttons and the values of the hidden fields. Now, you can write conditions for the actions to run. I didn't write complete code here, just passing the idea.
Edit: See the example below.
<form method="post" id="cart">
<table>
<input type="hidden" name="id" value='some value' />
<input type="submit" name="action" value="delete" />
<input type="submit" name="action" value="add" />
</tr>
<tr>
...
</tr>
</table>
<div><button type="submit">Update</button></div>
</form>
<?php print_r($_POST); ?>