Changing logic - jQuery - javascript

I have buttons that add and remove products from the Magento cart, but that's not so relevant in that issue. What I want to do is change the logic of what they are doing. Currently, when the buy button is clicked, the product is added to the cart, the button is "changed" to remove it and all other buttons are disabled for the click. When the remove button is clicked, the product that was added is removed and all other buttons can be clicked again.
I want to change the logic to the following: when the buy button is clicked, the product is added to the cart and the buy button is "changed" to remove (so far everything is the same as it was). But, all buttons remain click-enabled and if any other buy button is clicked, the product that was added is removed and the new product is added.
I've researched and thought in many ways, but I can not find a way to do that.
Button code:
<button type="button" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Add to Cart')) ?>" 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;" 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>Remover</span></span></button>
Ajax requisition code:
function addCartao(product_id){
$j('#cartaoMensagem'+product_id).hide();
$j('#cartaoMensagemRemover'+product_id).show();
$j('#cartaoMensagemRemover'+product_id).css({'background-color': '#000000'});
$j.ajax({
type: "POST",
url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>",
data: {
product_id: product_id
},
dataType: 'json',
cache : false,
beforeSend: function () {
},
success: function (retorno) {
var button = $j('#cartaoMensagemRemover'+product_id);
$j('#cartao').find(':button').not(button).attr('disabled',true);
$j('.item-custom').append('<tr id="trAppend"><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);
window.location.reload();
history.go(0);
window.location.href=window.location.href;
}
});
}
function removeCartaotoCart(itemId){
$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('#cartao').find(':button').attr('disabled',false);
$j('.item-custom #trAppend').remove();
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
window.location.reload();
history.go(0);
window.location.href=window.location.href;
}
});
}

I "simplified" your code a lot... Since I can't make an example with your PHP.
So the "reproduced" behavior is in this CodePen.
Now what you need to do, is to keep the added product ID in "memory" in a variable.
On add... If there already is a product ID, call the remove function, then add the other product.
It should be as simple as this.
So here is another CodePen with th modifications to make.
var productSelected = ""; // The variable used as a "memory".
function addCartao(product_id){
if( productSelected != "" ){
removeCartaotoCart(productSelected); // Remove the item in cart, if there is one.
}
console.log("Add "+product_id);
productSelected = product_id; // Keep the product id in "memory".
$('#cartaoMensagem'+product_id).hide();
$('#cartaoMensagemRemover'+product_id).show();
$('#cartaoMensagemRemover'+product_id).css({'background-color': '#000000','color':'white'});
//Ajax...
// In the success callback:
var button = $('#cartaoMensagemRemover'+product_id);
//$('#cartao').find(':button').not(button).attr('disabled',true); // Do not disable the other buttons.
}
function removeCartaotoCart(itemId){
console.log("Remove "+itemId);
productSelected = ""; // Remove the product id from "memory"
$('#cartaoMensagemRemover'+itemId).hide();
$('#cartaoMensagem'+itemId).show();
//Ajax...
// In the success callback:
var button = $('#cartaoMensagemRemover'+itemId);
//$('#cartao').find(':button').attr('disabled',false); // The other buttons aren't disabled... This line is useless.
}

Related

JQuery Event executed only once

I am trying to trigger a JQuery Ajax event for a bunch of buttons.
Here is the code in index.php file :
<?php
foreach($data as $d) {
$myid = $d['id'];
$mystatus = $d['status'];
?>
<div class="input-group-prepend">
<button id="submitbtn" type="button" class="myupdatebtn btn btn-success" data-id="<?php echo $myid; ?>" disabled>Finish Task</button></div>
<li class="nav-item">
<a class="nav-link clickable blueMenuItem" id="nav-location" data-id="<?php echo $d['id']; ?>">
<i class="nav-icon fas <?php echo $d['icon']; ?>"></i>
<p>
<?php echo $d["title"];
if ($d['type'] == "task") { ?>
<span id="updatemsg-<? echo $d['id'];?>" class="right badge <?php if($mystatus == "TERMINATED"){echo "badge-success";} else {echo "badge-danger";}?>"><?php setTerminated($conn, $myid)?></span>
<?php } ?>
</p>
</a>
</li>
<?php } ?>
Where the menu items (titles, status and icons) are extracted from a MySQL Database.
Here is the JAVASCRIPT (JQUERY) file with AJAX call :
$('.myupdatebtn').on('click', function() {
var id = $(this).data('id');
$.ajax({
url: 'includes/updatestatus.php',
type: 'POST',
data: {id:id},
dataType: 'html',
success: function(data)
{
if (data)
{
$('#submitComment').attr("disabled", true);
$('#customComment').val("");
$('#updatemsg-'+id).html("TERMINATED").removeClass('badge-danger').addClass('badge badge-success');
console.log(id);
}
else
{
$('#customContent').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$('#customContent').html("ERROR MSG:" + errorThrown);
}
});
});
This is the code for the updatestatus.php file :
<?php
include("db.php");
$id = $_POST['id'];
$query = "UPDATE mytable SET status='TERMINATED' WHERE id='$id'";
mysqli_query($conn, $query);
?>
As you can read from the code, when the button is clicked, it will be disabled and the input will be empty. The problem is that this code runs only once, after that the button will not updated the DATABASE and the DOM will not be updated (only after refresh and press the button again).
Is there a way to terminate the JQuery event after each iteration (Button pressed for every menu item) and make it available again to be executed?
You said you have "bunch of buttons.", I see only 1 in your code.
But if you have bunch of buttons with same class but different id, this code will work.
$('.myupdatebtn').each(function(){
$(this).on('click', function() {
var id = $(this).data('id');
$.ajax({
url: 'includes/updatestatus.php',
type: 'POST',
data: {id:id},
dataType: 'html',
success: function(data)
{
if (data)
{
$('#submitComment').attr("disabled", true);
$('#customComment').val("");
$('#updatemsg-'+id).html("TERMINATED").removeClass('badge-danger').addClass('badge badge-success');
console.log(id);
}
else
{
$('#customContent').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$('#customContent').html("ERROR MSG:" + errorThrown);
}
});
});
})
Give appropriate ids to buttons, so that your updatestatus.php works correctly.
$('.mybtn').each(function(){
$(this).click(function(){
alert("You clicked the button with id '"+this.id+"' call ajax do whatever");
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Bunch of buttons right?</h2>
<button id="1" class="mybtn">btn1</button><br/>
<button id="2" class="mybtn">btn1</button><br/>
<button id="3" class="mybtn">btn1</button><br/>
<button id="4" class="mybtn">btn1</button><br/>
<button id="5" class="mybtn">btn1</button><br/>
I couldn't understand what you meant by this 'Is there a way to terminate the JQuery event after each iteration (Button pressed for every menu item) and make it available again to be executed?', but as I know you need an active event listener, which triggers all the time button is clicked?
And one more thing I noticed, you are using if(data){//code} but what data?, you are not returning anything from php file, return something.
<?php
include("db.php");
$id = $_POST['id'];
$query = "UPDATE mytable SET status='TERMINATED' WHERE id='$id'";
if(mysqli_query($conn, $query)) echo "1";
else echo "2";
?>
Then use if(data === 1) {//do task} else if(data === 2){//Do else task}.

AJAX Response Issue in loop

I want ajax to update two different things. one is the clicked button class, and second is database record in while loop
Home
<?php
$q = mysqli_query($cn, "select * from `com`");
while ($f = mysqli_fetch_array($q)) {
?>
com: <?php echo $f['com']; ?><br>
<?php
$q1 = mysqli_query($cn, "select * from `fvc` where m_id='" . $f['id'] . "' and log='" . $_SESSION['id'] . "'");
$q2 = mysqli_query($cn, "select * from `fvc` where log='" . $_SESSION['id'] . "'");
?>
<span class="result<?php echo $f['id']; ?>">
<?php if (mysqli_num_rows($q1) > 0) { ?>
<button value="<?php echo $f['id']; ?>" class="unfc"><i title="<?php echo mysqli_num_rows($q2); ?>" class="fa fa-star" aria-hidden="true"></i></button>
<?php } else { ?>
<button value="<?php echo $f['id']; ?>" class="fc"><i title="<?php echo mysqli_num_rows($q2); ?>" class="fa fa-star-o" aria-hidden="true"></i></button>
<?php } ?>
</span>
<?php
}
?>
AJAX
$(document).ready(function(){
$(document).on('click', '.fc', function(){
var id=$(this).val();
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: id,
vote: 1,
},
success: function(){
showresult(id);
}
});
});
$(document).on('click', '.unfc', function(){
var id=$(this).val();
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: id,
vote: 1,
},
success: function(){
showresult(id);
}
});
});
});
function showresult(id){
$.ajax({
url: 'result.php',
type: 'POST',
async: false,
data:{
id: id,
showresult: 1
},
success: function(response){
$('.result'+id).html(response);
}
});
}
result.php
<?php
session_start();
include('cn.php');
if (isset($_POST['showresult'])){
$id = $_POST['id'];
$q3=mysqli_query($cn, "select * from `fvc` where m_id='".$id."' and log='".$_SESSION['id']."'");
$q4=mysqli_query($cn,"select * from `fvc` where log='".$_SESSION['id']."'");
$numFavs = mysqli_num_rows($q4);
if (mysqli_num_rows($q3)>0){
echo '<button class="unfc" value="'.$id.'"><i title="'.$numFavs.'" class="fa fa-star" aria-hidden="true"></i></button>' ;
} else {
echo '<button class="fc" value="'.$id.'"><i title="'.$numFavs.'" class="fa fa-star-o" aria-hidden="true"></i></button>' ;
}
}
?>
total number of row response is not updating for all comments in while loop.
I want loop ids to be updated as well in Ajax response for each comment So guide me whats wrong in my code
Your success function is targetting an element by ID, so a single specific element on the page. If you want to update multiple values you need to target a class or an element type which is common to the elements you want to target.
You have two classes for the buttons, so you could use those. You would have to change your PHP output so it just returns the new total number of likes, no HTML output needed.
Your success function in showLike would look something like this:
$(':button[value="'+id+'"]').toggleClass('favcom unfavcom');
$('.unfavcom').html('<i title="Remove from Favorite? - ('+response+'/20)" class="fa fa-star" aria-hidden="true"></i>');
$('.favcom').html('<i title="Favorite Comment - ('+response+'/20)" class="fa fa-star" aria-hidden="true"></i>');
Ofcourse it will update only one element, your show_like function updates only one element, the one with id = #show_like'+id
if you want to update all span elements, create a function update_likes() and call it in the success instead of show_like(),
$(document).on('click', '.favcom', function(){
var id=$(this).val();
$.ajax({
type: "POST",
url: "like.php",
data: {
id: id,
like: 1,
},
success: function(){
update_likes('.favcom');
}
});
});
then loop through the span elements and update each one of them, you can add a class .show_like if you have other spans and instead of $("span") put your class,
function update_likes(class){
$(class).each(function() {
show_like( $(this).val() );
});
}
i hope this works, however, this is based on your code and it will make a lot of http requests ( in show_like() ) and i would recommend you improve it by trying to return all the data you need and loop through an array instead of making Ajax calls every time.

Call Javascript Function in PHP Echo

With reference to This link
, I am trying to delete rows dynamically from a table. Here's my Javascript function:
function deleteBox(id){
alert ("Inside Method");
if (confirm("Are you sure you want to delete this record?"))
{
var dataString = 'id='+ id;
$("#flash_"+id).show();
$("#flash_"+id).fadeIn(400).html('<img src="img/loading.gif" /> ');
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(result){
if(result){
$("#flash_"+id).hide();
// if data delete successfully
if(result=='success'){
//Check random no, for animated type of effect
var randNum=Math.floor((Math.random()*100)+1);
if(randNum % 2==0){
// Delete with slide up effect
$("#list_"+id).slideUp(1000);
}else{
// Just hide data
$("#list_"+id).hide(500);
}
}else{
var errorMessage=result.substring(position+2);
alert(errorMessage);
}
}
}
});
}
}
However, calling it from Echo in Php, doesn't seem to invoke it. Here's my PHP code:
echo "<td align=\"center\">" . $id."</td>";
echo "<td><a href = 'javascript:deleteBox($id)'>Delete</a></td>";
Please correct me wherever I'm goin wrong. An early help would be highly appreciated.
<td><a href = 'javascript:deleteBox($id)'>Delete</a></td>
to
echo "<td><a onClick='deleteBox(" . $id . ");'>Delete</a></td>";
In my opinion, thats how I would do it..
Edited and shortened the jscript;
function deleteBox(idDelete){
alert ("Inside Method");
if (confirm("Are you sure you want to delete this record?"))
{
$("#flash_" + idDelete).show();
$("#flash_" + idDelete).fadeIn(400).html('<img src="img/loading.gif" /> ');
$.post('delete.php', {'id': idDelete}, function(result) {
if(result){
$("#flash_" + idDelete).hide();
// if data delete successfully
if(result=='success'){
//Check random no, for animated type of effect
var randNum=Math.floor((Math.random()*100)+1);
if(randNum % 2==0){
// Delete with slide up effect
$("#list_" + idDelete).slideUp(1000);
}else{
// Just hide data
$("#list_" + idDelete).hide(500);
}
}else{
var errorMessage=result.substring(position+2);
alert(errorMessage);
}
}
});
}
in your delete.php:
$_POST['id']
to retrieve the ID.
Check this, Hope this helps. Instead of id, static values are given
<td align="center">1</td>
<td><a href='#' onclick='deleteBox(1)'>Delete</a></td>
echo "<td><a href='#' onclick='deleteBox(1)'>Delete</a></td>";
jsfiddle
I am updating the answer, check whether alert is working.
<script>
function deleteBox(a){
alert(a);
}
</script>
<?php
echo "<a href='#' onclick='deleteBox(1)'>Delete</a>";
?>
Since you're using jQuery, I wouldn't do the call to the function in the href. Try something like this:
Javascript:
$(function() {
$('.delete').click(function() {
var id = $(this).attr('data-id');
alert ("Inside Method");
if (confirm("Are you sure you want to delete this record?"))
{
var dataString = 'id='+ id;
$("#flash_"+id).show();
$("#flash_"+id).fadeIn(400).html('<img src="img/loading.gif" /> ');
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(result){
if(result){
$("#flash_"+id).hide();
// if data delete successfully
if(result=='success'){
//Check random no, for animated type of effect
var randNum=Math.floor((Math.random()*100)+1);
if(randNum % 2==0){
// Delete with slide up effect
$("#list_"+id).slideUp(1000);
}else{
// Just hide data
$("#list_"+id).hide(500);
}
}else{
var errorMessage=result.substring(position+2);
alert(errorMessage);
}
}
}
});
});
});
PHP/HTML:
echo "<td align=\"center\">" . $id."</td>";
echo "<td><a class='delete' data-id='" . $id . "'>Delete</a></td>";

Auto refresh controller and view Yii

How i could make this page auto refresh/update every 10 second when there is/isnt data update. Like Twitter when there is a new tweet.
Example : This is in first second.
You have 1 name with no status
Then after 10 second, there is an event that "name" data have been added.
You have 2 names with no status
what should i do? I've tried with javascript, but it wont refresh the data from controller.
this is my actioncheckNames Controller
public function actioncheckNames() {
//Check Name with No Status
$noStat = new CDbCriteria();
$noStat->condition = "status IS NULL";
$noStat->order = "name ASC";
$sums = Name::model()->count($noStat);
//End of Check Function
return array('sum'=>$sums);
}
And this is sort of my index on view.
<script>
$(document).ready(function() {
setInterval(function() {
$.ajax({
url: '<?php echo $this->createUrl('name/checkNames'); ?>'
, type: 'post'
, success: function(data) {
if (data) {
$("#checkname");
}
}
});
}, 5000 //5 seconds
);
});
</script>
<div id="checkname">
<?php
if ($sum != 0) {
?>
<div class="alert alert-block alert-primary fade in">
<button data-dismiss="alert" class="close" type="button">X</button>
<h4 class="alert-titleing">You Have <?php echo $sum ?> Names With No Status. <font color="White"><u>Check</u></font> </h4>
</div>
<?php }
?>
</div>
*Update : create actionCheckNames Controller and add ajax script. but my web wont refresh the data.
You can refresh your page by JS set interval + AJAX request & can try something like below
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: '<?php echo $this->createUrl('controller/action');?>'
,type: 'post'
//,data: {var1: val1, var2: val2,....}
,success: function(data){
if(data){
//Refresh your div/html element by appending here...
}
}
});
},10000 //10 seconds
);
});

Jquery radio button submit repeats same value multiple times

I have problems creating report system. Plan is this: User has 4 radios to select and then submits one of them. First submission inserts only one row in mysql but every after that submission inserts more and more rows. Here is the code:
profile.php
<form id="myform">
bully<input type="radio" id='radio<?php echo $outid; ?>' name="nein" class='radspam' value="bulinput"> </input><br>
spam<input type="radio" id='radio<?php echo $outid; ?>' name="nein" class='radspam' value="spaminput"> </input><br>
viol<input type="radio" id='radio<?php echo $outid; ?>' name="nein" class='radspam' value="vioinput"> </input><br>
pron<input type="radio" id='radio<?php echo $outid; ?>' name="nein" class='radspam' value="pcont_input"> </input>
</form>
///jquery code
$(".report").click(function(){
var parent=$(this).parent().attr("id");
var split=parent.split("output");
var id=split[1];
loading();
closeloading(); // fadeout loading
$(".torep").fadeIn("fast"); // fadein popup div
$("#backgroundPopup").css("opacity", "0.7"); // css opacity, supports IE7, IE8
$("#backgroundPopup").fadeIn("fast");
$("input:radio[name=nein]").click(function() {
$(".repyes").removeAttr("disabled");
});
$(".repyes").click(function(){
var username="<?php echo $username; ?>";
var valara = $('input:radio[name=nein]:checked').val();
$.ajax({
url:"s/report.php",
data:"username=" + username + "&what=" + valara + "&whatid=" + id,
type:"POST",
success:function(data){
alert(data);
$(this).prop('checked', false);
}
});
});
});
report.php
<?php
include "db.php";
IF (isset($_POST['whatid'])){
$what=$_POST['what'];
$reported=$_POST['username'];
$whatid=$_POST['whatid'];
$sql=mysql_query("INSERT INTO report(reported,what,whatid,date) VALUES ('$reported','$what','$whatid',now())");
if (mysql_affected_rows() == 1){
echo "udje";
}else{
echo mysql_error();
}
}
?>
Move id to global scope. And assign click event to .repyes outside of $(".report").click():
var _id = null;
$(".report").click(function(){
var parent=$(this).parent().attr("id");
var split=parent.split("output");
_id = split[1];
loading();
closeloading(); // fadeout loading
$(".torep").fadeIn("fast"); // fadein popup div
$("#backgroundPopup").css("opacity", "0.7"); // css opacity, supports IE7, IE8
$("#backgroundPopup").fadeIn("fast");
$(".report").click(function() {
$("input:radio[name=nein]").click(function() {
$(".repyes").removeAttr("disabled");
});
});
});
$(".repyes").click(function(){
var username="<?php echo $username; ?>";
var valara = $('input:radio[name=nein]:checked').val();
$.ajax({
url:"s/report.php",
data:"username=" + username + "&what=" + valara + "&whatid=" + _id,
type:"POST",
success:function(data){
alert(data);
$(this).prop('checked', false);
}
});
});
It most likley is because you have an event handler binding inside an event handler. So everytime you click report a new click event is bound to .repeyes
$(".report").click(function(){
...
$(".repyes").click(function(){
Just move the second binding outside of the first one.
UPDATE
Oh, the id issue should be fixed like in Arthur Halma'S answer by moving it to global scope.

Categories

Resources