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

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);
});

Related

How can I use JS attribute for links in PHP?

trying to understand.
I have a js code,
$(document).on('click','.plan_btn',function() {
$('.ui-dropdown').removeClass('active');
var tarifplanid=$(this).attr('data-tarifplanid');
$('.planid').text(tarifplanid);
$('.add_plan').addClass('show');
});
I have a php code, with button, where I pass attr.
<button type="button" class="ui-component ui-button plan_btn" data-tarifplanid="<?php echo($plan->plan_id)?>">Select</button>
So, by pressing Select button, I will have an planID, which is 2 or 3 stored in .JS
Then, as test, I have the following code:
<?php
$test = <<<EOD
<span class="planid"></span>
EOD;
echo $test;?>
Question is:
echo returns ID, 2 or 3, depends on which item I pressed "Select"
But, when I trying to add a link with $test, it will as <span class="planid"></span>
Why? I assume it should be https://localhost/2 but I have https://localhost/<span class="planid"></span>
Thank you!
I'm not a developer, just browsing and a learning a bit

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>

Dynamically change Button functionality on onclick event

I would like to have a single button that does 2 functions without having to refresh or visit another page. 1. First will be Add to Cart button when clicked it will add a product to a cart and once the product is added to cart the button should 2. change to Remove from cart and when clicked Remove from cart button it should remove the item from cart and again change the button again back to Add to cart.
Right now I am using very simple onclick event button
<button class="btn btn-sm btn-inverse btn-embossed" onclick="ajaxSubmit('/add/product/<?php echo $productId; ?>/"><span><?php echo $this->__('Add to Cart') ?></span></button>
Product can be removed with url below
/remove/product/<?php echo $productId ?>/
I have already tried several options from other forums but I couldn't achieve it.
I suggest you to move your ajax call from onclick event so you don't need o duplicate long code. Second add parameters like current action and id to data for jQuery access.
$('.product-btn').click(function(){
if($(this).attr('data-action')=="add"){
ajaxSubmit('/add/product/'+$(this).attr('data-id')+'/');
$(this).attr('data-action','remove');
$(this).children('span').html('Remove from cart');
}else{
ajaxSubmit('/remove/product/'+$(this).attr('data-id')+'/');
$(this).attr('data-action','add');
$(this).children('span').html('Add to cart');
}
});
<button class="btn btn-sm btn-inverse btn-embossed product-btn" data-action="add" data-id="<?php echo $productId; ?>"><span><?php echo $this->__('Add to Cart') ?></span></button>

How to add a delete button in custom table in yii

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.

Categories

Resources