How to add a delete button in custom table in yii - javascript

I have a form where I use ajaxSubmitButton to add product items in a HTML table. ajaxSubmitButton helps to use ajax to add item, ajax url take the values and update the table's body <tr>, <td>. In table, I want to keep a delete button in last column in every rows. When I click the delete button, a row should be deleted. But here delete button does not work. I have checked the hardcoded HTML table and jquery in views that works.
In this circumstance, how could I solve this issue. Please help me. I have given below the form and controller's code:
Form:
Yii::app()->clientScript->registerScript('removecartitem', "
$('#remove').click(function(){
$('#cartDetails tr:first').remove();
})
");
?>
<div class="form-group">
<div class="col-lg-2">
<?php
// this is the ajax submit button
echo CHtml::ajaxSubmitButton('Add Item',Yii::app()->createUrl('admin/order/cart'),
array(
'type'=>'POST',
'update'=>'#cartTable',
),
array('class'=>'btn btn-primary btn-sm',));
?>
</div>
</div>
<div class="form-group">
<div class="col-lg-12">
<table id="cartDetails" class="table table-bordered sortableTable responsive-table">
<tbody id="cartTable"> // ajax updates this id
</tbody>
</table>
</div>
</div>
In controller:
public function actionCart()
{
if(isset($_POST["Order"])){
.....
.....
$cartDetails = Yii::app()->session['cart'];
if(!empty($cartDetails)){
foreach($cartDetails as $cart){
echo '<tr>';
echo '<td>'.$cart["product_id"].'</td>';
echo '<td>'.$cart["product_name"].'</td>';
echo '<td>'.$cart["product_code"].'</td>';
echo '<td>'.$cart["quantity"].'</td>';
echo '<td>'.$cart["price"].'</td>';
echo '<td>'.$cart["totalPrice"].'</td>';
echo '<td><input type="button" name="add" id="remove" value="Remove" class="btn btn-danger btn-xs"/></td>';
echo '</tr>';
}
}
}
At this stage, none of jquery works. Please help how to enable jquery then how to activated the delete button. Please let me know if my explanation is not clear. I have added an images to explain more clear.

alter so you have a class for removal, for example
public function actionCart()
{
if(isset($_POST["Order"])){
.....
.....
$cartDetails = Yii::app()->session['cart'];
if(!empty($cartDetails)){
foreach($cartDetails as $cart){
.
.
.
echo '<td>'.$cart["totalPrice"].'</td>'; // see below line , class : REMOVETHIS
echo '<td><input type="button" name="doesntMatter" class="REMOVETHIS btn btn-danger btn-xs"/></td>';
.
}
}
}
then on page ready, remove it on click
$(document).ready(function(){
$('.REMOVETHIS').click(function(){
$(this).parent().parent().remove();
});
});
UPDATE:
the code below will only remove first row of table,
$('#cartDetails tr:first').remove();
and I'm guessing even this wont work, because jquery needs to be used after document ready. like :
$(document).raady(function(){
//put jquery related code in here
});
and like our friend said, you can NOT assign multiple elements with the same id, for that you better use classes,
and in this case because the row inserted to table is fresh, you need to state again
$('.REMOVETHIS').click(function(){
$(this).parent().parent().remove();
});
after you have inserted the row, or you can do this:
echo '<td><input type="button" name="doesntMatter" class="btn btn-danger btn-xs" onclick="removeRow(this)"/></td>';
and when that element is clicked, removeRow function will be called
function removeRow(element)
{
$(element).parent().parent().remove();
}

As how I solve my problem:
I have an order from where I place order for registrants. In the order form, there are 3 fields i select registration, select product, then quantity. There is a ajaxSubmitButton what sends this value to the controller (actionCart). Controller saves the value i.e. product id, name, price, quantity, total price in session and update the ajax request in tabular format to the order form. During echoing <tr>, <td> I added a button to delete item from session. So, I want to delete value of session as well as the row of table once click button. But button did not work because jquery did not work although I saw that jquery was loaded.
I found that ajax updated HTML did not work with earlier loaded jquery. So I changed the strategy that separated Updated HTML table (what I echoed in controller) in another view file and used renderPartial into the controller. I injected my required Jquery snippets into the view file. Then I found that jquery is responding with ajax requested HTML tags.
Now I am working forward to unset the session array and row of table using jquery and ajax.

Related

How to use data-attribute to pass values from database to jquery

I have an issue passing values from a database to a modal pop up using data attribute.
My problem is the data-attribute value passes only one value whereas the edit button is in a php loop and should pick the value for each row.
Below is a part of my loop code:
<td>
<p data-placement="top" data-toggle="tooltip" title="Edit">
<a href="<?php echo admin_url('admin.php?page=woocommerce_checkout&id=' . $query->id.'&status=update'); ?>"
class="btn btn-primary btn-xs updatesection"
data-title="Edit"
data-toggle="modal"
data-id="<?php echo $query->id ?>"
data-target="#editbilling"
data-name="<?php echo $query->name; ?>">Edit</a>
</p>
</td>
js
$(document).on( "click", '#editbilling', function(e) {
var data = $('.updatesection').data('name');
alert(data);
});
So I am testing the values passed through the data attribute by alerting it on javascript.
The problem is only the first id gets submitted for all the edit buttons in a loop carrying different ids instead of submitting different ids for each row in the database.
When I inspect the code on the browser I discover the data-attributes have the corresponding values from the database but they don't get submitted - only the first row gets submitted for all the edit buttons in the loop.
Can anyone find a fix to this please
I changed the id onclick to class and then used attr instead of data and it worked. Please check my solution below:
$(document).on( "click", '.updatesection', function(e) {
var data = $(this).attr('data-id');
alert(data);
});

fetch data without reloading by passing a variable to jquery

I want to fetch some data (without reloading page) based on UserIds that are linked to a tags. I am not able to pass on UserID to jquery successfully and accurately. What it does is, just picks the last UserID and fetches it.
I have also tried to pass on variable throuh a-tag URL but could not get it accurately in jquery file. It fetches the data from already opened url, not the one being clicked right now.
HTML:
<?php foreach($Messagers as $Messagers1){ ?>
<form action="" method="post">
<input type="hidden" id="ANP" value="<?php echo ($Messagers1['UserID']*3);?>"></input>
<a class="LoadMsgsBtn">
Click to load data
</a>
</form>
<?php}?>
<div id="result">
<--The output will come here!-->
</div>
jquery:
$(document).ready(function(){
$(".LoadMsgsBtn").click(function LoadMsgsfunc(){
var ANP = $("input#ANP").val();
var Msg=6;
alert(ANP);
$("#result").load("LoadDB.php",{
ANP: ANP,
Msg: Msg
});
})
});
LoadDB.php:
<?php
$ID = $_POST['ANP'];
$Msg = $_POST['Msg'];
echo $ID . "\n";
echo $Msg;
I want to fetch data from database without reloading using UserID sent. $Messager is an array having multiple rows, there is a series of a-tags. clicking on any a-tag sents corresponding UserID to jquery code
Classic issue of multiple element selection. It's a bit tricky when you are using loops and jquery selectors ;) Check out the following code. It should work like butter B)
<?php foreach($Messagers as $Messagers1){ ?>
<form action="" method="post">
<a class="LoadMsgsBtn" href="javascript:void(0)" onclick="featchData('<?php echo ($Messagers1['UserID']*3);?>')">
Click to load data
</a>
</form>
<?php}?>
<div id="result">
<--The output will come here!-->
</div>
Javascript
function featchData(userId)
{
console.log(userId);
//if you get the id, write in the rest of the code here ;)
}

send ID (dynamically created in php) from a href tag to ajax/jquery?

I have a question, I'm very new to jQuery and Ajax, so I hope someone can help me.
I have multiple 'edit' buttons in table ((1.st column data)for each row data -> (2.nd column action) button edit), and I've created some inline-editing function in jQuery: but when I click on edit button to show data in table and edit, they are all opening at once, I want to open only for instance first to edit.
I assigned every edit button id in element dynamically.
I'm assuming I have to send that id button to a Ajax, so it can proceed, but I don't know how and what to do? I hope someone could explain me. Thank you very much!!!
Here is my code:
php
<?php
$teams = Team::getAll();
foreach ($teams as $team) {
$tname = $team->name;
$tid = $team->team_id;
echo "<tr><td><a href='#' class='editable' style='margin-left: 2px;'>".$tname."</a><form method='POST' action=''><input type='text' class='editshow form-control col-sm-3 ' aria-label='Sizing example input' aria-describedby='inputGroup-sizing-sm' name='edit_name' value='".$tname."'><button name='btnSave' style='margin-left: 2px; margin-top:3px;' class='btn btn-success btn-sm editshow'>Save</button></form></td>";
echo "<td><a href='teams.php?edit_tid=$tid'><button class='btn btn-primary btn-sm btnEdit'".$tid."'>Edit</button></a><a href='teams.php?delete_tid=$tid'><form method='POST' action=''><button name='btnDelete' class='btn btn-danger btn-sm'>Delete</button></form></a></td></tr>";
}
?>
jQ
<script type="text/javascript">
$(".editshow").hide();
$(".btnEdit").click(function(){
$(".editshow").toggle();
$(".editable").setTimeout(2000);
});
</script>
You're very close -- basically, you want to be able to reference the specific button that was clicked, then get to its related edit fields.
<script type="text/javascript">
$(".editshow").hide();
$(".btnEdit").click(function(){
// We'll save a reference to the current button...
let clickedBtn = $(this),
containerEl = clickedBtn.closest("tr");
// now, we can work specifically within this TR el, as that is
// the container for our currently editing data.
containerEl.find(".editshow").toggle();
containerEl.find(".editable").setTimeout(2000);
});
</script>
Using jQuery's closest() gets me to the nearest <tr>, which is the container for the current table row. By limiting the selections to THAT (using containerEl.find()), I am only toggling elements related to this particular row.
I do recommend taking a look at the jQuery docs, there are some complex things happening here. First, the $(this) within the click handler refers to the clicked element. Second, you might want to look at the docs for both .closest() and .find().
Not sure what the setTimeout() is meant to be doing, but that should get you started.
Hope it helps!

Uncaught SyntaxError: Unexpected token < while calling cakephp select form directly in javascript

i have a basic problem related to javascript and PHP,
I am trying to include a select option in javascript. For debug purpose I did the same with input text box and it works fine. As soon as i load the options using cakephp form helper through a list of array passed from controller i get this above error. I will explain what i am trying to achieve with code example:
i have a form and a div tag where i want to append a select options using javascript, jquery in my case.
my view file:
<?php echo $this->Form->create('GenericDrug'); ?>
<div class="voca">
</div>
<button type="button" class="btn btn-success btn-add" >
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Add more
</button>
<?php echo $this->Form->end(); ?>
Values passed from my controller:
public function admin_edit($id = null) {
//other codes
$this->set(compact('drugClasses','genericDrugs','drugClassList'));
}
these classes are modeled using ORM
Now i want a jquery/javascript function such that it will append my select option in div tag classed as 'voca'.
So far i have done:
In my view file:
<script type="text/javascript">
var i = <?php echo $this->Form->input('drug_class_id'); ?>
$(function()
{
$(document).on('click', '.btn-add', function(e)
{
$(i).appendTo( ".voca" );
</script>
input drugclassid will generate list of options for select. However, I tried a lot of fiddling around but cant find a solution. The page does get rendered at the backend and sends all the option data, however i get a javascript error message
Click to see error message
Try it
<script>
var myvar = <?php echo json_encode($this->Form->input('drug_class_id')); ?>
</script>

Show PHP object data inside javascript

I know there have been just too many questions so far asking about PHP and JS working together...I went through them, but I cannot find an elegant solution for my use case.
What I currently have is following PHP code in my webpage that fetches product info and shows it:
<?php
$p= new Product($prodId);
$p->getProductInfo();
//now show product info...
echo "<div>Product Name: ".$p['productName']."</div>";
echo "<div>Product Rating: ".$p['productRating']."</div>";
//etc...
?>
Now what I have been asked to do is instead of showing this data directly in the page, I should show it only when a button is clicked. And I should show it inside a bootbox modal dialog box
So I did:
<span id='prod-details'> View Product Details </span>
<input type='hidden' id ='prod-id' value='<?php echo $p['productId'];?>'>
And in my jquery file I have:
$('#prod-details').click(function(
var prodId = $('#prod-id').val();
productDetail = "Product Details for "+prodId;
//how do I get rest of product details from PHP object?
bootbox.alert(productDetail);
));
Any help is very much appreciated...I have been trying hard to make this work.
What I normally do is echo the information inside the bootbox modal div and just hide/show the bootbox modal div with an onClick function
you can either put it in your html file like this:
<script>
var productName = <?php echo $p['productName'];?>;
</script>
or exactly like you did with the product id, just put all the data you need inside the input div (or any oher div releated to that product)
<input type='hidden' id ='prod-id' value='<?php echo $p['productId'];?>' productName='<?php echo $p['productName'];?>'>
and then using jquery get that data like you got the id
var prodName = $('#prod-id').attr('productName');

Categories

Resources