i have this code in index.php:
<tbody>
<?php foreach($data as $fetch): ?>
<tr>
<input type="hidden" name="user_id" value="<?php echo $_SESSION['user_id']?>">
<td class="segment" contenteditable="true"><?= $fetch['segment'] ?></td>
<td class="text-center">
<button class = "btn btn-default action-btn" data-id="<?= $fetch['id'] ?>" data-action="update">
<span class = "glyphicon glyphicon-edit"></span> Update
</button>
|
<button class = "btn btn-success activate-btn action-btn" data-id="<?= $fetch['id'] ?>" id="<?= $fetch['id'] ?>" type="submit" data-action="activate">
<span class = "glyphicon glyphicon-check"></span> Activate
</button>
<button style="display:none" class = "btn btn-danger deactivate-btn action-btn " data-id="<?= $fetch['id'] ?>" id="<?= $fetch['id'] ?>" data-action="deactivate">
<span class = "glyphicon glyphicon-folder-close"></span> deactivate
</button>
<button style="display:none" class = "btn btn-danger deactivate-btn action-btn " data-id="<?= $fetch['id'] ?>" data-action="deactivate">
<span class = "glyphicon glyphicon-folder-close"></span> deactivate
</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<form action="create.php" method="post" class="form-inline">
<div class = "form-group">
<label>Segment:</label>
<input type = "text" name = "segment" class = "form-control" required = "required"/>
</div>
<div class = "form-group">
<button type="submit" name = "save" class = "btn btn-primary"><span class = "glyphicon glyphicon-plus"></span> Add</button>
</div>
</form>
<script type="text/javascript">
$(".action-btn").on("click", function(e) {
var id = $(this).attr("data-id");
var segment = $(this).parents("tr").find("td.segment").html();
var action = $(this).attr("data-action");
$.ajax({
"url": "action.php",
"method": "post",
"data": {
"id": id,
"segment": segment,
"action": action
},
success: function(data) {
alert(data);
}
});
}); </script>
$(".action-btn").click(function(){
$(this).hide();
$("#"+id).show();
});$(".deactivate-btn").click(function(){
$(this).show();
$("#"+id).show();});</script> </body></html>
and in action .php i have this code
<?php require_once 'class.php';require './session.php';if (!isset($_POST['action'])) { exit;}$action = $_POST['action'];$segment =$_POST['segment'];$id = $_POST['id'];$change='update';switch($action) {
case "update":
$conn = new db_class();
$conn->update($segment, $id,$change);
exit;
case "activate":
$activation = '1';
$conn = new db_class();
$conn->activate($activation, $id);
exit;
case "deactivate":
$activation = '0';
$userID= $_SESSION['user_id'];
$conn = new db_class();
$conn->activate($activation, $id);
exit;}?>
the problem is when i click on any activate button all deactivate button doesnt show and when i refresh the page the activate button show up like i didnt do anything please help me
Please change
from:
$(".action-btn").on("click", function(e) {
To:
$(document).on("click",".action-btn", function(e) {
because the html is dynamic created over the document.
Thanks
First check this script function working or not by console...Always try to use $(document).ready(function(){ // Do your work }); when you are in DOM
$(".action-btn").on("click", function(e) {
var id = $(this).attr("data-id");
var segment = $(this).parents("tr").find("td.segment").html();
var action = $(this).attr("data-action");
$.ajax({
"url": "action.php",
"method": "post",
"data": {
"id": id,
"segment": segment,
"action": action
},
success: function(data) {
alert(data);
$(".action-btn").hide(); //this will hide your submit button
}
})
});
//to deaactivate button
$(".deactivate-btn").on("click", function(e) {
$(".action-btn").show();
$(".deactivate-btn").hide();
});
problem in your code is
after ajax call jquery does not work with
$(".deactivate-btn").click(function(){
$(this).show();
$("#"+id).show();
});
direct click
Hope you will find answer
Related
I have an HTML that gets its values from an array list. I'm submitting the form with Ajax and with a PHP script. The issue I'm facing is when clicking on the other array it only submits the first value array. Below is what my form looks like with the PHP loop of array listing:
index.php
$query_product = "SELECT * FROM products ORDER BY id DESC";
$product_stmt = $conn->prepare($query_product);
if($product_stmt->execute()){
while($row_product = $product_stmt->fetch(PDO::FETCH_ASSOC)){
$id = $row_product["id"];
$title = $row_product["title"];
$description = $row_product["description"];
$price = $row_product["price"];
$img = $row_product["img"];
?>
<form onsubmit="clickButton()">
<input type="hidden" value="<? echo $title ?>" name = "title" id="title" >
<input type="hidden" value="<? echo $id ?>" name = "id" id="id" >
<input type="hidden" value="<? echo $price; ?>" name="price" id="price">
<input type="hidden" value="<? echo $img; ?>" name="img_src" id="img_src">
<button type="submit" id="add_to_cart" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart" onclick="return clickButton();">Add Cart</button>
</form>
<?php
}
}
?>
My Ajax looks like the below:
<script type="text/javascript">
function clickButton(){
var title = $("#title").val();
var price = $("#price").val();
var img_src = $("#img_src").val();
var id = $("#id").val();
alert(title);
$("#add_to_cart").attr("disabled", true);
$.ajax({
type:"post",
url:"my_add_cart.php",
data:
{
'title' :title,
'price' :price,
'img_src' :img_src,
'id' :id
},
cache:false,
beforeSend: function(){
$("#loading").show();
},
complete: function(){
$("#loading").hide();
},
success: function (data)
{
// alert(data['message']);
//enable loading
$("#add_to_cart").attr("disabled", false);
$('#msg').html(data['message']);
$('#count').html(data['count']);
}
});
return false;
}
</script>
When I tried to alert(title); above it return just the first array value even though I click the other arrays.
If you ignore the need for a form as you are using ajax you could streamline your code so that each record displays a single button that has various attributes set which are read by the javascript click handler and used to construct the payload sent via ajax to the php server.
$query_product="SELECT * FROM products ORDER BY id DESC";
$product_stmt = $conn->prepare( $query_product );
if( $product_stmt->execute() ){
while( $rs = $product_stmt->fetch( PDO::FETCH_ASSOC ) ){
printf(
'<input type="button" class="btn btn-outline-secondary btn-sm ajax" value="Add to cart" data-id="%s" data-title="%s" data-price="%s" data-img="%s" />',
$rs["id"],
$rs["title"],
$rs["description"],
$rs["price"],
$rs["img"]
);
}
}
?>
<script>
document.querySelectorAll('input.ajax').forEach( bttn => bttn.addEventListener('click',function(e){
let fd=new FormData();
fd.set( 'id', this.dataset.id );
fd.set( 'title', this.dataset.title );
fd.set( 'price', this.dataset.price );
fd.set( 'img_src', this.dataset.img );
alert( this.dataset.title );
$.ajax({
type:"post",
url:"my_add_cart.php",
data:fd,
cache:false,
beforeSend: function(){
$("#loading").show();
},
success:function( data ){
$("#add_to_cart").attr("disabled", false);
$('#msg').html(data['message']);
$('#count').html(data['count']);
},
complete: function(){
$("#loading").hide();
}
});
}))
</script>
So I was able to solve this myself by adding the ID of each item from the loop to the ID of the input form in the HTML making the ID of each item unique. Below is how I solved it:
<form onsubmit="clickButton(<? echo $id ?>)">
<input type="hidden" value="<? echo $title ?>" name = "<? echo $id.'_title' ?>" id="<? echo $id.'_title' ?>" >
<input type="hidden" value="<? echo $id ?>" name = "<? echo $id.'_id' ?>" id="<? echo $id.'_id' ?>" >
<input type="hidden" value="<? echo number_format($price); ?>" name = "<? echo $id.'_price' ?>" id="<? echo $id.'_price' ?>" >
<input type="hidden" value="<? echo "url".$row_product_img[0]; ?>" name = "<? echo $id.'_img_src' ?>" id="<? echo $id.'_img_src' ?>">
<button type="submit" id="add_to_cart" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart" onclick="return clickButton(<? echo $id ?>);">Add Cart</button>
</form>
And my Javascript is as below:
<script type="text/javascript">
function clickButton(id){
var title=document.getElementById(id+'_title').value;
var price=document.getElementById(id+'_price').value;
var img_src=document.getElementById(id+'_img_src').value;
var id=document.getElementById(id+'_id').value;
$("#add_to_cart").attr("disabled", true);
$.ajax({
type:"post",
url:"my_add_cart.php",
data:
{
'title' :title,
'price' :price,
'img_src' :img_src,
'id' :id
},
cache:false,
beforeSend: function(){
$("#loading").show();
},
complete: function(){
$("#loading").hide();
},
success: function (data)
{
// alert(data['message']);
//enable loading
$("#add_to_cart").attr("disabled", false);
$('#msg').html(data['message']);
$('#count').html(data['count']);
}
});
return false;
}
</script>
I am getting "Uncaught ReferenceError is not defined" error when I am going to call the updateinventory() function from the appended update button. I don't know what is the problem.
<script type="text/javascript">
$("i").click(function() {
var id = this.id;
var product_code = $('#pr_code'+id).val();
var user_id = $('#user_id'+id).val();
var qty = $('#qtyspan_'+id).text();
$('#qtyspan_'+id).css('display', 'none');
$('#'+id).css('display', 'none');
$('#simplyupdate'+id).append('<div id="updateinventorydiv'+id+'" class="input-group" style="width: 227px;"><div class="form-group"><input type="hidden" id="pr_coding" value="'+id+'"/><input value="'+qty+'" type="text" class="form-control input-sm"></div><span class="input-group-btn"><button onclick="updateinventory('+product_code+','+user_id+','+id+')" class="btn btn-success btn-sm" type="button">Update</button><button id="canceldiv_'+id+'" class="btn btn-danger btn-sm" type="button">cancel</button></span></div>');
});
function updateinventory(product_code,user_id,outlet_id) {
alert(product_code);
}
</script>
PHP file: This is the PHP code where I have created 3 hidden inputs to get the ids in JavaScript.
for ($t = 0; $t < count($outletData); ++$t) {
$outlet_id = $outletData[$t]->id;
$outlet_name = $outletData[$t]->name;
?>
<div class="row" style="padding-top: 5px; padding-bottom: 5px;">
<div class="col-md-3">
<?php echo $outlet_name; ?>
</div>
<div class="col-md-9" id="simplyupdate<?php echo $t; ?>">
<?php
$invQty = 0;
$invQtyData = $this->Constant_model->getDataTwoColumn('inventory', 'product_code', $code, 'outlet_id', $outlet_id);
if (count($invQtyData) > 0) {
$invQty = $invQtyData[0]->qty;
}
?>
<span id="qtyspan_<?php echo $t; ?>"><?php echo $invQty; ?></span>
<input type="hidden" id="pr_code<?php echo $t; ?>" value="<?php echo $code; ?>" />
<input type="hidden" id="user_id<?php echo $t; ?>" value="<?php echo $user_role; ?>" />
<input type="hidden" id="outlet_id<?php echo $t; ?>" value="<?php echo $outlet_id; ?>" />
<i class="fa fa-pencil" id="<?php echo $t; ?>"></i>
</div>
</div>
<?php
}
?>
The issue is the updateinventory arguments not beeing quoted.
It should be:
<button onclick="updateinventory(\''+product_code+'\',\''+user_id+'\',\''+id+'\')" class="btn btn-success btn-sm" type="button">Update</button>
Notice the backslashes \ to escape them... Pretty complicated. So beyond that, here is a better way to achieve the same. You use jQuery... So do not use the inline onclick=....
Give your button a class... Say update. Then use delegation on it, since it is appended (dynamically created).
About the product_code, user_id and id, first store it in some data attributes and on button click, retreive the values using .data().
I made the changes below... Untested ;) Try it.
$("i").click(function() {
var id = this.id;
var product_code = $('#pr_code'+id).val();
var user_id = $('#user_id'+id).val();
var qty = $('#qtyspan_'+id).text();
$('#qtyspan_'+id).css('display', 'none');
$('#'+id).css('display', 'none');
$('#simplyupdate'+id).append('<div id="updateinventorydiv'+id+'" class="input-group" style="width: 227px;"><div class="form-group"><input type="hidden" id="pr_coding" value="'+id+'"/><input value="'+qty+'" type="text" class="form-control input-sm"></div><span class="input-group-btn"><button data-productcode="'+product_code+'" data-userid="'+user_id+'" data-id="'+id+'" class="btn btn-success btn-sm update" type="button">Update</button><button id="canceldiv_'+id+'" class="btn btn-danger btn-sm" type="button">cancel</button></span></div>');
});
$(document).on("click",".update",function(){
var product_code = $(this).data("productcode");
console.log(product_code);
});
I have three sections in my working code:
a PHP file,
a jQuery code section which contains an AJAX function which requests,
another PHP file.
The response is a HTML section which should be prepended to a DIV inside the first PHP file (from where AJAX was requested using the jQuery section in the <script> tag inside the <head> section of the PHP file.
My query is while AJAX is prepending dynamically the HTML successfully in the desired DIV element id="content", the other click events targeted with response HTML element tags are not working dynamically.
What could be the reason?
$(".update_button").click(function (){
var updateval = $("#update").val();
var cate = $("#selectcategory").val();
var up = $("#uploadvalues").val();
if (up)
{
var uploadvalues = $("#uploadvalues").val();
}
else
{
var uploadvalues = $(".preview:last").attr('id');
}
var X = $('.preview').attr('id');
if (X)
{
var Z = X + ',' + uploadvalues;
}
else
{
var Z = 0;
}
var dataString = 'update=' + updateval + '&Category=' + cate + '&uploads=' + Z;
if ($.trim(updateval).length == 0 || $("#selectcategory").val() === "")
{
if ($.trim(updateval).length == 0)
{
alert('Please Enter SOME TEXT!');
}
else if ($("#selectcategory").val() === "")
{
alert('Choose a Category from the list!');
}
}
else
{
$.ajax({
type: "POST",
url: $.base_url + "message_ajax.php",
data: dataString,
cache: false,
success: function (html)
{
$("#flash").fadeOut('slow');
$(".teacherpost").prepend(html);
$("#update").val('').focus();
$("#selectcategory").val('');
$('#preview').html('');
$('#uploadvalues').val('');
$('#photoimg').val('');
$(".decoration").hide();
}
});
}
return false;
});
HTML prepended from AJAX resposne:
<div class="post-description">
<div class="stats">
<div class="st_like_share">
<a class="Like" href="javascript:void(0)" id='like<?php echo $msg_id;?>' title='<?php echo $like_status;?>' rel='<?php echo $like_status;?>' data='<?php echo $shareKey; ?>'><i class="glyphicon glyphicon-star" style="color:#F16522;"></i><?php echo $like_count; ?></a>
<?php } else { ?>
<a class="Like" href="javascript:void(0)" id='like<?php echo $msg_id;?>' title='<?php echo $like_status;?>' rel='<?php echo $like_status;?>' data='<?php echo $shareKey; ?>'><i class="glyphicon glyphicon-star" ></i><?php echo $like_count; ?></a>
<?php } ?>
<a href="javascript:void(0)" class="stat-item remark" data-id="<?php
echo $msg_id;?>" title='Give your Remarks on it'>
<i class="fa fa-comments-o icon"></i><?php echo $remark_count; ?>
</a>
<a href="javascript:void(0)" class="stdelete stat-item" data-id="<?php echo $omsg_id;?>" rel="" title="Delete Post">
</a>
<?php }
?>
</div>
</div>
</div>
<div class="post-footer" id="post-footer-<?php echo $msg_id;?>">
<textarea name="comment" class="form-control add-comment-input" id="ctextarea<?php echo $omsg_id;?>" style="width:100%;" placeholder="Add a remark here..."></textarea>
<span class="input-group-btn">
<input type="submit" value="Remark" name="Remark" id="<?php echo $omsg_id;?>" rel="<?php echo $msg_id;?>" class="btn btn-info pull-right Remark_button">
<!--<input type="submit" id="" value="Send" class="btn btn-default go-chat pull-right ">-->
</span>
<?php if($remark_count>0) { ?>
<ul class="comments-list" id="commentload<?php echo $msg_id;?>">
<?php include('comments_load.php'); ?>
</ul>
<?php } ?>
</div>
</div>
jQuery which is not working on the AJAX responded HTML code:
/*Remark Load */
$(".stat-item.remark").on("click", function( e ) {
var post_footer_id = "#post-footer-"+$(this).data('id');
$(post_footer_id).slideToggle();
});
Dynamically this is not working, but when I refresh the page this jQuery works fine.
Try like this
$(document).on('click', '.stat-item.remark', function(){
var post_footer_id = "#post-footer-"+$(this).data('id');
$(post_footer_id).slideToggle();
});
$.ajax({
type: "POST",
url: $.base_url + "message_ajax.php",
data: dataString,
cache: false
})
.done((data) => {
//on success code here
})
.fail((jqXhr) => {
//on failure code here
//jqXhr.responseJSON
});
For standard opencart behavior, after adding the product in cart, user needs to click to update button manually for quantity update. For sample, please refer to http://demo.opencart.com/. However, I would like to change to when I change the quantity, the cart info can be refreshed immediately. I've tried following code but it doesn't work:
For catalog/view/theme/default/template/checkout/cart.tpl, I updated:
button type="submit" data-toggle="tooltip" title="" class="btn btn-primary">
i class="fa fa-refresh">/button>
(don't know why I cannot paste the code properly on the above line. I've removed some < to make it show)
to
<button type="button" data-toggle="tooltip" title="<?php echo $button_update; ?>" class="btn btn-primary" onchange="cart.update('<?php echo $product['key']; ?>', '<?php echo $product['quantity']; ?>');"><i class="fa fa-refresh"></i></button>
In catalog/view/javascript/common.js
There is a function
var cart = {
//skip some lines for other function
'update': function(key, quantity) {
$.ajax({
url: 'index.php?route=checkout/cart/edit',
type: 'post',
data: 'key=' + key + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json',
beforeSend: function() {
$('#cart > button').button('loading');
},
complete: function() {
$('#cart > button').button('reset');
},
success: function(json) {
// Need to set timeout otherwise it wont update the total
setTimeout(function () {
$('#cart > button').html('<img src="image/catalog/content/cart/quote-icon.png" alt="quote"><span class="badge badge-giftu rounded-x">' + json['totallines'] + '</span>');
}, 100);
if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
$('#cart > ul').load('index.php?route=common/cart/info ul li');
} else {
$('#cart > ul').load('index.php?route=common/cart/info ul li');
}
}
});
},
}
I tried if I change to cart.remove under the on.change function, it works. However, it doesn't work for cart.udpate. Is there anyone know what is the issue of triggering the ajax update issue?
I myself had such a problem solved it like this
Old code (i have custom them):
<input type="text" name="quantity[<?php echo $product['key']; ?>]" value="<?php echo $product['quantity']; ?>" size="1" class="form-control"/>
<span class="input-group-btn">
<button type="submit" data-toggle="tooltip" title="<?php echo $button_update; ?>" class="btn btn-primary"><i class="fa fa-refresh"></i></button>
<button type="button" data-toggle="tooltip" title="<?php echo $button_remove; ?>" class="btn btn-danger"
onclick="cart.remove('<?php echo $product['key']; ?>');"><i class="fa fa-times-circle"></i></button>
New Code (fixed) look on input and Remove(button type="button" If he also does not work)
<input type="text" name="quantity[<?php echo $product['cart_id']; ?>]" value="<?php echo $product['quantity']; ?>"
size="1" class="form-control"/>
<span class="input-group-btn">
<button type="submit" data-toggle="tooltip" title="<?php echo $button_update; ?>"
class="btn btn-primary"><i class="fa fa-refresh"></i></button>
<button type="button" data-toggle="tooltip" title="<?php echo $button_remove; ?>" class="btn btn-danger"
onclick="cart.remove('<?php echo $product['cart_id']; ?>');"><i class="fa fa-times-circle"></i></button>
There was a problem that incorrectly gave the notation for the fields it was necessary to put the key in the cart_id
I want to hide a row after a delete query is done.
When i do this
<?php echo '<input type="submit" name="editProject'; echo $projectID; echo '" value="Edit" class="btn btn-success"/>';?>
The record will be deleted in the database but the row doesn't hide.
This
<input type="button"
Will hide the row but doesn't delete the record in the database.
So how can i delete a record in the database and hide that row together.
form in table:
<td class="deleterow"><form action="index.php" method="post">
<?php echo '<button type="button" name="deleteProject'; echo $projectID; echo '" class="btn-sm btn btn-danger"><span class="glyphicon glyphicon-remove"></span></button>';?>
</form></td>
Javascript:
<script>
$(".deleterow").on("click", function(){
var $killrow = $(this).parent('tr');
$killrow.addClass("danger");
$killrow.fadeOut(2000, function(){
$(this).remove();
});});
</script>
You have to make an ajax call in order to achieve this functionality. I assume you have jQuery in your project.
$(".deleterow").on("click", function(){
var $killrow = $(this).parent('tr');
$killrow.addClass("danger");
$killrow.fadeOut(2000, function() {
$(this).remove();
$.post("delete.php", {id: "<?php echo $projectID; ?>"})
.done(function(data) {
alert("Project deleted: " + data);
});
});
});
I only added this part.
$.post("delete.php", {id: "<?php echo $projectID; ?>"})
.done(function(data) {
alert("Project deleted: " + data);
});