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
});
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 wrote below code for woocommerce that when quantity is less than one, click link of remove in cart, but after clicking, the page refreshed, while with mouse, fire ajax without refreshing page.
document.querySelector('.product-details a[data-product_id="' + product_id + '"] ').click()
The below code is for min cart on top page that show quantity and has remove links.I want to use the this remove link.
<div class="pull-right top-cart hidden-xs">
<div class="tbay-topcart">
<div id="cart" class="dropdown version-1 open">
<span class="text-skin cart-icon">
<i class="icofont-shopping-cart"></i>
<span class="mini-cart-items" style="opacity: 1;"> 4 </span>
</span>
<a class="dropdown-toggle mini-cart" data-toggle="dropdown" aria-expanded="true" role="button"
aria-haspopup="true" data-delay="0" href="#" title="Show cart">
<span class="sub-title">My cart<i class="icofont-rounded-down"></i> </span>
<span class="mini-cart-subtotal" style="opacity: 1;"><span class="woocommerce-Price-amount amount">20,000 <span
class="woocommerce-Price-currencySymbol">$</span></span><i
class="icofont-rounded-down"></i></span>
</a>
<div class="dropdown-menu">
<div class="widget_shopping_cart_content" style="opacity: 1;">
<div class="mini_cart_content">
<div class="mini_cart_inner">
<div class="mcart-border">
<ul class="cart_list product_list_widget ">
<li id="mcitem-30da227c6b5b9e2482b6b221c711edfd">
<a href="/product/%d8%ac%d8%b3%d8%a8-%da%a9%d8%aa%d8%a7%d8%a8/">
<img width="160" height="130"
src="wp-content/uploads/2019/12/7-cm-90-yard-45-micron-1-160x130.png"
class="attachment-woocommerce_gallery_thumbnail size-woocommerce_gallery_thumbnail wp-post-image"
alt="book"> </a>
<div class="product-details">
<a href="/cart/?remove_item=30da227c6b5b9e2482b6b221c711edfd&_wpnonce=bebb559ebd"
class="remove remove_from_cart_button" aria-label="remove-this-item"
data-product_id="4465" data-product_sku=""
data-cart_item_key="30da227c6b5b9e2482b6b221c711edfd">x</a>
book
<span class="quantity">1</span>
<span class="woocommerce-Price-amount amount">8,000 <span
class="woocommerce-Price-currencySymbol">$</span></span></div>
</li>
</ul><!-- end product list -->
<p class="total">total: <span class="woocommerce-Price-amount amount">20,000 <span
class="woocommerce-Price-currencySymbol">$</span></span></p>
<p class="buttons">
cart
checkout
</p>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
This code worted in quantity php that shows in under my products, when I clicked on minus or plus, change data attribute of element add_to_cart
<div class="box-quantity">
<span class="title-qty"><?php echo esc_html__( 'Quantity', 'greenmart' ) ?></span>
<div class="quantity">
<input class="minus" type="button" value="-">
<input
type="number"
class="input-text qty text"
data-step="<?php echo esc_attr( $step ); ?>"
data-min="<?php echo esc_attr( $min_value ); ?>"
data-max="<?php echo esc_attr( 0 < $max_value ? $max_value : '' ); ?>"
name="<?php echo esc_attr( $input_name ); ?>"
value="<?php echo esc_attr( $input_value ); ?>"
title="<?php echo esc_attr_x( 'Qty', 'Product quantity input tooltip', 'greenmart' ) ?>"
size="4" pattern="<?php echo esc_attr( $pattern ); ?>"
data-inputmode="<?php echo esc_attr( $inputmode ); ?>"
aria-labelledby="<?php echo esc_attr( $labelledby ); ?>" />
<input class="plus" type="button" value="+">
</div>
</div>
the below code is my script, first, I checked that data attribute (add to cart) changed then update my cart.
but I can not remove one product from my cart without refresh page.
<script>
const x_elements = [...document.querySelectorAll('.ajax_add_to_cart')];
let observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
let product_id = mutation.target.getAttribute('data-product_id');
const product_qty = mutation.target.getAttribute(mutation.attributeName);
let current_val = mutation.target.getAttribute(mutation.attributeName);
console.log(mutation.target.getAttribute(mutation.attributeName) + '-' + mutation.target.getAttribute('data-product_id') + '-' + mutation.oldValue);
let minus_action =
document.querySelector('[data-product-id="' + product_id + '"] input.minus');
let plus_action =
document.querySelector('[data-product-id="' + product_id + '"] input.plus');
if (current_val == '0') {
minus_action.style.opacity = 0;
minus_action.disabled = true;
} else if (current_val == '1') {
minus_action.value = '×';
minus_action.style.opacity = 1;
minus_action.disabled = false;
} else {
minus_action.value = '-';
minus_action.style.opacity = 1;
minus_action.disabled = false;
}
minus_action.addEventListener('click', () => {
if (current_val == '0' || current_val == 0 || current_val < 1 || mutation.oldValue == 0 &¤t_val == 1 ) {
document.querySelector('.product-details a[data-product_id="' + product_id + '"] ').click();
console.log('clicked= '+document.querySelector('.product-details a[data-product_id="' + product_id + '"] '))
}
});
const data = {
action: 'woocommerce_add_2_cart',
product_id: product_id,
product_qty: product_qty,
product_qty_old: mutation.oldValue
};
jQuery.ajax({
type: 'post',
url: woocommerce_params.ajax_url,
data: data,
beforeSend: function (response) {
minus_action.parentNode.style.opacity='.5';
minus_action.disabled='true';
plus_action.disabled='true';
},
complete: function (response) {
minus_action.parentNode.style.opacity='1';
minus_action.disabled='false';
plus_action.disabled='false';
},
success: function (response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
var fragments = response.fragments;
if (fragments) {
jQuery.each(fragments, function (key, value) {
jQuery(key).replaceWith(value);
});
}
}
},
});
});
});
x_elements.forEach(ele => {
ele.setAttribute('data-quantity', '0');
observer.observe(ele, {
attributes: true,
attributeOldValue: true,
attributeFilter: ['data-quantity']
}
);
});
</script>
You have defined "href" in anchors. So mimicking click do redirect as expected. You can set href="#" in anchors. But on the other hand, I do not understand why clicking with mouse does not redirect the page. I'm a bit confused.
I have newsletter subscribe input in opencart website and when i input email and press subscribe it says "Email is not valid!: even thou it is.
So i cant use it since it doesnt take emails.
I used this theme and didnt change anything in the subscribe module,
you can scroll down to the footer and check how it behaves here: http://demopavothemes.com/pav_woosa/demo2/
Cant figure out what is the problem.
Heres the code of the module:
<div class="<?php echo $prefix; ?> newsletter-v1" id="newsletter_<?php echo $position.$module;?>">
<form id="formNewLestter" method="post" action="<?php echo $action; ?>" class="formNewLestter">
<div class="panel panel-v1">
<div class="panel-heading">
<h4 class="panel-title"><?php echo $objlang->get("entry_newsletter");?></h4>
</div>
<div class="panel-body">
<div class="input-group">
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
<div class="input-group-btn pull-left">
<button type="submit" name="submitNewsletter" class="btn btn-primary icon-mail radius-6x"><?php echo $objlang->get("button_subscribe");?></button>
</div>
</div>
<input type="hidden" value="1" name="action">
<div class="valid space-top-10"></div>
</div>
<?php if (!empty($social)): ?>
<?php echo html_entity_decode( $social );?>
<?php endif ?>
</div>
</form>
</div>
<script type="text/javascript"><!--
$( document ).ready(function() {
var id = 'newsletter_<?php echo $position.$module;?>';
$('#'+id+' .box-heading').bind('click', function(){
$('#'+id).toggleClass('active');
});
$('#formNewLestter').on('submit', function() {
var email = $('.inputNew').val();
$(".success_inline, .warning_inline, .error").remove();
if(!isValidEmailAddress(email)) {
$('.valid').html("<div class=\"error alert alert-danger\"><?php echo $objlang->get('valid_email'); ?><button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div></div>");
$('.inputNew').focus();
return false;
}
var url = "<?php echo $action; ?>";
$.ajax({
type: "post",
url: url,
data: $("#formNewLestter").serialize(),
dataType: 'json',
success: function(json)
{
$(".success_inline, .warning_inline, .error").remove();
if (json['error']) {
$('.valid').html("<div class=\"warning_inline alert alert-danger\">"+json['error']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
if (json['success']) {
$('.valid').html("<div class=\"success_inline alert alert-success\">"+json['success']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
}
});
return false;
});
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
--></script>
This line:
$('.inputNew')
is looking for a class named inputNew. Your HTML doesn't have an element with that name. Your element it looks like has a class of email.
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
^^^^^
You also could use the form-control but that doesn't sound unique. An id would be better or you could use the name attribute like this:
$('input[name="email"]')
so change the JS line to:
var email = $('.email').val();
or
var email = $('input[name="email"]').val();
You can read more about these here, https://api.jquery.com/category/selectors/.
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
I have a button that calls an ajax once you submit but I need to add another input where you have to enter text and if that text is the same as the text found in the DB this button should execute the AJAX. How can this be done?
This is my AJAX code:
<script>
jQuery(function(){
jQuery(".canjear").click(function(e){
if(this.tagName==="A"){
e.preventDefault();
}
jQuery.ajax({
url: "index.php?option=com_cuphoneo&task=miscuponess.canjearCupon",
type: "POST",
data: {id:jQuery(this).data("id")},
success: window.location.href = "index.php?option=com_cuphoneo&view=miscuponess&layout=default"
});
});
});
</script>
This is my PHP/HTML button:
<div class="panel-boton-canjear">
<?php
foreach($campos_extra as $value){
if($value->id == 17){
if(!empty($value->value)){
?>
<input class="canjear btn" type="button" value="<?php echo JText::_('COM_CUPHONEO_BOTON_CANJEAR'); ?>" data-id="<?php echo $valor->item_id; ?>" />
<?php
}
}
}
?>
</div>