newajax onclick not working for dynamically created items - javascript

I have a table where users can add rows using jquery. This is all working fine to a point. the problem I have is the dynamically created row has a button with an onclick event that connect to new Ajax code to browse from computer. The problem is button work in first generated row but when i generated another the button not work .
This is the button with onclick event:
<a onclick="image_upload('image<?php echo $image_row; ?>', 'thumb<?php echo $image_row; ?>');" id="simple-image<?php echo $image_row; ?>" class="upimage"><?php echo $text_browse; ?></a>
New Ajax code for event :
function image_upload(field, thumb ){
new AjaxUpload('#simple-image' + <?php echo $image_row; ?>, {
action: 'index.php?route=common/filemanager/upload&image=' + encodeURIComponent($('#' + field).attr('value')),
name: 'image',
autoSubmit: true,
responseType: 'json',
onChange: function(file, extension) {
this.setData({'directory': ''});
this.submit();
},
onSubmit: function(file, extension) {
$('#simple-image' + <?php echo $image_row; ?>).append('<img src="catalog/view/theme/default/image/loading.gif" class="loading" style="padding-left: 5px;" />');
},
onComplete: function(file, json) {
if (json.success) {
$('#' + field).attr('value','data/user/'+file);
$.ajax({
url: 'index.php?route=common/filemanager/image&image=' + encodeURIComponent($('#' + field).attr('value')),
dataType: 'text',
success: function(text) {
$('#' + thumb).replaceWith('<img src="' + text + '" alt="" id="' + thumb + '" />');
}
});
}
if (json.error) {
alert(json.error);
}
$('.loading').remove();
}
});
};
Any help will be much appreciated.

<?php $iid = 0; ?>
<a onclick="image_upload('image<?php echo $image_row; ?>', 'thumb<?php echo $image_row; ?>','simple-image<?php echo $image_row.$iid; ?>');" id="simple-image<?php echo $image_row.$iid++; ?>" class="upimage"><?php echo $text_browse; ?></a>
function image_upload(field, thumb , idd ){
new AjaxUpload('#'+idd , {
action: 'index.php?route=common/filemanager/upload&image=' + encodeURIComponent($('#' + field).attr('value')),
name: 'image',
autoSubmit: true,
responseType: 'json',
onChange: function(file, extension) {
this.setData({'directory': ''});
this.submit();
},
onSubmit: function(file, extension) {
$('#simple-image' + <?php echo $image_row; ?>).append('<img src="catalog/view/theme/default/image/loading.gif" class="loading" style="padding-left: 5px;" />');
},
onComplete: function(file, json) {
if (json.success) {
$('#' + field).attr('value','data/user/'+file);
$.ajax({
url: 'index.php?route=common/filemanager/image&image=' + encodeURIComponent($('#' + field).attr('value')),
dataType: 'text',
success: function(text) {
$('#' + thumb).replaceWith('<img src="' + text + '" alt="" id="' + thumb + '" />');
}
});
}
if (json.error) {
alert(json.error);
}
$('.loading').remove();
}
});
};

Related

AJAX doesn't update post when PHP code stored inside .html function

I'm having a bit of confusion on why the PHP variables used in the html variable that I inserted inside the .ajax success function doesn't update my post automatically, but works fine when using the data parameter I supplied in the success function.
The reason I prefer inserting data I got from my controller is I need to use some Codeigniter functions, which I cannot do with the latter.
This version of my function where I utilized the data parameter is working fine, but I need to use the word_limiter() function from Codeigniter to reduce the post length
Version using data parameter
function showFeed() {
$.ajax({
type: 'ajax',
url: '<?= base_url()?>feed/showfeed',
async: false,
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<div class="my-3">' +
'<h2>'+ data[i]['title'] + '</h2>' +
'<span class="post-date text-center px-2 py-1"> Posted on ' + data[i]['created_at'] + ' </span>' +
'<p class="my-2">' + data[i]['body'] + '</p><br>' +
'<div class="col-6 offset-3">' +
'<img class="post-image" src="<?= site_url();?>/assets/images/posts/' + data[i]['post_image'] + '"></div>' +
'<div class="my-5">' +
'<a class="btn btn-dark float-left mr-2" href="http://localhost/ci-socmed/post/' + data[i]['slug'] +'">Read More</a>' +
'<form action="http://localhost/ci-socmed/feed/delete/' + data[i]['id'] + '"method="post" accept-charset="utf-8">' +
'<input type="submit" value="Delete" class="btn btn-danger float-left mr-2">' +
'</form>' +
'<a class="btn btn-primary text-white float-left" id="btnEdit" data-toggle="modal" data-target="#editModal" data="' + data[i]['id'] + '">Edit Post</a>' +
'</div></div><div class="clearfix"></div>'
}
$('#nf-post').html(html);
},
error: function() {
alert('Error');
}
});
}
Version with using data from Feed controller
function showFeed() {
$.ajax({
type: 'ajax',
url: '<?= base_url()?>feed/showfeed',
async: false,
dataType: 'json',
success: function() {
var html = '';
html +=
'<?php foreach ($feed as $post): ?>' +
'<div class="my-3">' +
'<h2><?= $post['title'] ?></h2>' +
'<span class="post-date text-center px-2 py-1">Posted on <?= $post['created_at'] ?></span>' +
'<p class="my-2"><?= word_limiter($post['body'], 30) ?></p><br>' +
'<div class="col-6 offset-3">' +
'<img class="post-image" src="<?= site_url();?>/assets/images/posts/<?= $post['post_image'] ?>"></div>' +
'<div class="my-5">' +
'<?php if($this->session->userdata('user_id') == $post['user_id']): ?>' +
'<a class="btn btn-dark float-left mr-2" href="http://localhost/ci-socmed/post/<?= $post['slug']?>">Read More</a>' +
'<form action="http://localhost/ci-socmed/feed/delete/<?= $post['id'] ?>"method="post" accept-charset="utf-8">' +
'<input type="submit" value="Delete" class="btn btn-danger float-left mr-2">' +
'</form>' +
'<a class="btn btn-primary text-white float-left" id="btnEdit" data-toggle="modal" data-target="#editModal" data="<?= $post['id'] ?>">Edit Post</a>' +
'<?php endif; ?>' +
'</div></div><div class="clearfix"></div>' +
'<?php endforeach ?>'
$('#nf-post').html(html);
},
error: function() {
alert('Error');
}
});
}
JQuery function for editing post
$(document).on('click', '#btnEdit', function() {
var id = $(this).attr('data');
$('#editModal').modal('show');
$('#editModal').find('.modal-title').text('Edit Post');
$('#modalForm').attr('action', '<?= base_url() ?>feed/update');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>feed/edit',
data: {
id: id
},
async: false,
dataType: 'json',
success: function(data) {
$('textarea[name=edit-body]').val(data.body);
$('input[name=post-id]').val(data.id);
},
error: function() {
alert('Could not Edit Data');
}
});
});
Feed controller
class Feed extends CI_Controller
{
public function index($page = 'index')
{
if (!file_exists(APPPATH . 'views/feed/' . $page . '.php')) {
show_404();
}
$data['title'] = ucfirst($page);
$data['feed'] = $this->Feed_mdl->get_feed();
$this->form_validation->set_rules('post-text', '', 'required', array('required' => 'Your post is empty.'));
if ($this->form_validation->run() === FALSE) {
$this->load->view('templates/header');
$this->load->view('feed/' . $page, $data);
$this->load->view('templates/footer');
}
}
}
My showfeed() function
public function showfeed() {
$this->db->order_by('id', 'desc');
$query = $this->db->get('feed');
if($query->num_rows() > 0){
return $query->result();
}else{
return false;
}
}
When I'm using the version which retrieves data from the Feed controller, the database updates it except that I need to refresh the page in order to see whatever changes I made to my post, unlike the other version.
EDIT
Just checked that I put the wrong code on the second showfeed() function, where I used the $data['feed] object from the Feed controller, in which if I used this version of showfeed(), I'm reloading the page manually in order to view changes I've made in my post. Sorry for the confusion.

Like Dislike with single checkbox php ajax

I have checked all related questions on SO, but still looking for the best answer.
I am coding a review system where anyone can comment and logged in users can like their review (Like or undo their like only ...not dislike).
For that, I am using a checkbox and onClick call an ajax function that will like the review and if click again it will undo the action.
problem
Initially, When someone like the review, ajax call will like it and on Success it will change attr onClick to unlike(); function but again when i click on it it does not work fine...
MY TRY
<?php if($review['is_liked']){ ?>
<input type="checkbox" name="review_like" id="<?php echo $review['review_id'] . '-' . $review['customer_id'] . '-' . $review['product_id']; ?>" checked="checked" onclick="unlike(<?php echo $review['review_id'] . '-' . $review['customer_id'] . '-' . $review['product_id']; ?>);" />
<?php } else { ?>
<input type="checkbox" name="review_like" id="<?php echo $review['review_id'] . '-' . $review['customer_id'] . '-' . $review['product_id']; ?>" onclick="like(<?php echo $review['review_id'] . '-' . $review['customer_id'] . '-' . $review['product_id']; ?>);" />
<?php } ?>
And JS (id passing to JS func looks like 1105-249532-18117)
<script>
function unlike(id){
console.log('unlike');
var id2 = toString(id).split('-');
console.log('Unlike: '+id);
console.log('split id: '+ id2);
$.ajax({
url: 'index.php?route=product/product/like_review',
type: "get",
data: {
'is_liked': 1,
'review_id': id[0],
'customer_id': id[1],
'product_id': id[2]
},
dataType: 'json',
success: function(json) {
console.log(json);
$('.btn-thumbs-up').find('input[type=checkbox][name=review_like]').attr("onclick","like(id);");
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
function like(id){
console.log('like');
console.log('Liked: '+id);
var id2 = toString(id).split('-');
console.log('split: '+id2);
$.ajax({
url: 'index.php?route=product/product/like_review',
type: "get",
data: {
'is_liked': 0,
'review_id': id[0],
'customer_id': id[1],
'product_id': id[2]
},
dataType: 'json',
success: function(json) {
console.log(json);
$('.btn-thumbs-up').find('input[type=checkbox][name=review_like]').attr("onclick","unlike(id);");
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
the id i am passing to like/unlike function is not working fine in console and also split function even use toString func or wdout...
Please fix this or suggest better way to do this task...
You could handle it at client side with simpler conditions. Change the <input> tag to:
<input type="checkbox" name="review_like" data-id="<?php echo $review['review_id']; ?>" data-customer="<?php echo $review['customer_id'] ?>" data-product="<?php echo $review['product_id']; ?>" checked="<?php echo ( $review['is_liked'] ? "checked" : ""); ?>" />
And add this jQuery script to handle the checkbox change:
$('input[name="review_like"]').change ( function ()
{
$.ajax (
{
url: 'index.php?route=product/product/like_review',
type: "get",
data:
{
'is_liked': $(this).prop('checked'),
'review_id': $(this).data ( 'id'),
'customer_id': $(this).data ( 'customer'),
'product_id': $(this).data ( 'product')
},
dataType: 'json',
success: function ( json)
{
console.log ( ( $(this).prop('checked') ? 'Unliked' : 'Liked') + ' review ' + $(this).data ( 'id') + ', customer ' + $(this).data ( 'customer') + ', product ' + $(this).data ( 'product'));
},
error: function ( xhr, ajaxOptions, thrownError)
{
alert ( thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});

Value changed to null in ajax

Value changed to null in ajax after updating the shipping city value from text field. I don't known what is the problem.. please help me Friends.
my php code:
public function updateshippingcity() {
if ($this->request->server['REQUEST_METHOD'] == 'POST')
{
$json['new_shipping_city'] = $this->request->post['shipping_city'];
$this->db->query("UPDATE " . DB_PREFIX . "order SET shipping_city = '" . $this->db->escape($this->request->post['shipping_city']) . "' WHERE order_id = '" . (int)$this->request->get['order_id'] . "'");
$this->response->setOutput(json_encode($json));
}
}
my ajax code :
<script type="text/javascript">
$("#update-shipping-city").click(function() {
var name_val = $('input[name="new_shipping_city"]').val();
$.ajax({
url: 'index.php?route=sale/order/updateshippingcity&token=<?php echo $token; ?>&order_id=<?php echo $order_id; ?>',
type: 'post',
dataType: 'json',
data: {
shipping_city: name_val
},
beforeSend: function() {
$('#update-shipping-city').attr('disabled', true);
},
complete: function() {
$('#update-shipping-city').attr('disabled', false);
},
success: function(json) {
}
});
alert("shipping city has changed");
});
my html code:
<div class="col-md-12">
<input name="new_shipping_city" value="<?php echo $shipping_city; ?>"></input>
<button id="update-shipping-city" > update </button>
</div>
I had achieved finally by post method.
<script type="text/javascript">
$(function() {
$("#update-shipping-city").click(function(e) {
e.preventDefault();
var scity_val = $('input[name="new_shipping_city"]').val();
$.post("index.php?route=sale/order/updateshippingcity&token=<?php echo $token; ?>&order_id=<?php echo $order_id; ?>", {
shipping_city: scity_val
}, function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
});
});
Finally, my problem cleared. thank guys for contributing on my question :)

Removing cart products from input with product id value

I wanted to work with input type ="hidden" so I can do a check. I have a slider which displays products of a category and through two Ajax requests I add and remove them through clicks on buy and remove buttons, however that does not have as much relevance in this question.
Only one such product on the slide can be purchased by order, but if one of them is added and the page is updated and the buy button is clicked again, another of that product is added, which should not happen. I wanted to make sure that in the update of the page, if there is already one of these products added, it is removed, but I do not know where to follow it to complete it.I think I should use an input type ="hidden", so that through it I can save the value of the id of the added product, but I do not know how to do this verification.
Below I will add the code of the buttons and the input that I have already made and are correct, besides the code of the Ajax requisitions. If necessary, I add the code of the controllers I use.
Button and input code:
<button style="margin-left: 11%;" type="button" class="button btn-cart" onclick="addCartao('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>" id="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
<button style="display: none; margin-left: 11%;" type="button" id="cartaoMensagemRemover<?php echo $_product->getId(); ?>" title="Remover" class="button btn-cart" onclick="removeCartaotoCart('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span>Remove</span></span></button>
<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="" />
Ajax requisition code:
var productSelected = "";
function addCartao(product){
if( productSelected != "" ){
removeCartaotoCart(productSelected); // Remove the item in cart, if there is one.
}
$j('#cartaoMensagem'+product).hide();
$j('#cartaoMensagemRemover'+product).show();
$j('#cartaoMensagemRemover'+product).css({'background-color': '#000000'});
$j.ajax({
type: "POST",
url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>",
data: {
product: product
},
dataType: 'json',
cache : false,
beforeSend: function () {
},
success: function (retorno) {
var button = $j('#cartaoMensagemRemover'+product);
productSelected = product;
$j('#cartaoMensagemAdicionado').val(productSelected);
$j('.item-custom').append('<tr id="trAppend'+product+'"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>');
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
function removeCartaotoCart(itemId){
productSelected = "";
$j('#cartaoMensagemRemover'+itemId).hide();
$j('#cartaoMensagem'+itemId).show();
$j.ajax({
type:"POST",
url:"<?php echo Mage::getUrl('fol_carousel/ajax/removeCartao') ?>",
data:{
itemId: itemId
},
cache: false,
beforeSend: function(){
},
success: function(retorno){
var button = $j('#cartaoMensagemRemover'+itemId);
$j('#cartaoMensagemAdicionado').val(productSelected);
$j('.item-custom #trAppend'+itemId+'').remove();
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
What you should do is make a small php code to do the verification, where it contains the SKUs of these products and if they are in the cart, assign a value to a boolean variable and insert it into an input to work this value in jQuery.
Php code for verification:
<?php
$array_de_skus_de_cartoes = array(45,60,80,90,102,103,104,105); //SKUs of products
$isCartaoAdicionado = 0;
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item) {
foreach ($array_de_skus_de_cartoes as $sku) {
if($sku == $item->getProduct()->getSku()) {
$isCartaoAdicionado = 1;
$cartao_id = Mage::getModel("catalog/product")->getIdBySku($sku);
}
}
}
if($isCartaoAdicionado == 1) {
?>
<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="1" />
<input type="hidden" name="cartao_adicionado_product_id" id="cartao_adicionado_product_id"" value="<?php echo $cartao_id ?>" />
<?php
}
else {
?>
<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="0" />
<input type="hidden" name="cartao_adicionado_product_id" id="cartao_adicionado_product_id"" value="" />
<?php
}
?>
Ajax request code updated:
var isCartaoAdicionado = $j('#cartao_adicionado').val();
var isCartaoAdicionadoProductId = $j('#cartao_adicionado_product_id').val();
var productSelected = "";
function addCartao(product){
if(isCartaoAdicionado == 1){
removeCartaotoCart(isCartaoAdicionadoProductId);
}
if( productSelected != "" ){
removeCartaotoCart(productSelected); // Remove the item in cart, if there is one.
}
$j('#cartaoMensagem'+product).hide();
$j('#cartaoMensagemRemover'+product).show();
$j('#cartaoMensagemRemover'+product).css({'background-color': '#000000'});
$j.ajax({
type: "POST",
url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>",
data: {
product: product
},
dataType: 'json',
cache : false,
beforeSend: function () {
},
success: function (retorno) {
var button = $j('#cartaoMensagemRemover'+product);
productSelected = product;
$j('#cartaoMensagemAdicionado'+product).val(productSelected);
$j('.item-custom').append('<tr id="trAppend'+product+'"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>');
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
function removeCartaotoCart(itemId){
productSelected = "";
$j('#cartaoMensagemRemover'+itemId).hide();
$j('#cartaoMensagem'+itemId).show();
$j.ajax({
type:"POST",
url:"<?php echo Mage::getUrl('fol_carousel/ajax/removeCartao') ?>",
data:{
itemId: itemId
},
cache: false,
beforeSend: function(){
},
success: function(retorno){
var button = $j('#cartaoMensagemRemover'+itemId); $j('#cartaoMensagemAdicionado'+itemId).val(productSelected);
$j('.item-custom #trAppend'+itemId+'').remove();
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}

How to trigger a close event in lightbox_me

I tried all the things but none of them are working.
Here is the code to call the lightbox_me:
$('#buynow').click(function(e) {
$('#pop').lightbox_me({
centered: true,
});
e.preventDefault();
});
And I am calling close function using a href link:
function close()
{
$('#pop').trigger('close');
}
I am sending ajax request to get the car product
$("#buynow").click(function() {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "displaycart.php",
data: '1',
cache: false,
success: function(result) {
$('#pop').html(result);
}
});
return false;
});
I am getting all the values from another file which contains html code
here is that code
while ($fetch_pro = mysql_fetch_array($pro)) {
$product = mysql_query("select * from product where id ='" . $fetch_pro['pro_id'] . "'");
while ($fetch_product = mysql_fetch_array($product)) {
echo '<tr><td class="padd_botton">';
echo '<img src = "images/product_images/'.$fetch_product['image'].'" height="60px" width="60px" >';
echo '</td><td class="padd_botton">';
echo '</td><td class="padd_botton">';
echo $fetch_product['product_name'].'<br> Remove ';
echo '</td><td class="padd_botton">';
echo '</td><td class="padd_botton">';
echo '<input class="textqua" id="qty'.$fetch_pro['id'].'" type="text" value="'.$fetch_pro['qua'].'" onchange="javascript:update('.$fetch_pro['id'].');" >';
echo '</td><td class="padd_botton">';
echo '</td><td class="padd_botton">';
echo 'Rs.'.$fetch_product['price'];
echo '</td><td class="padd_botton">';
echo '</td><td class="padd_botton">';
$total = $fetch_pro['qua'] * $fetch_product['price'];
echo '<span style="color:#6e8a02">Rs.'.$total.'</span>';
echo '</tr>';
$final_total = $total+$final_total;
}
}

Categories