I'm using click function to get the current ID of the clicked form, then running submit form function to apply my code.
But once I click to run the function the code doesn't apply, I've tried to debug the code to find out what causing this problem, it's seems like the click function works properly, but the submit function doesn't work at all.
The submit function is working if there weren't any click function wrapping it.
<form method="POST" class="<?php echo $row['code']; ?>" id="form<?php echo $row['id']; ?>">
<a id="submit" class="product-links" id="cartsub" href='javascript:addCart(<?php echo $row['id']; ?>);'>
<i class="fa fa-shopping-cart"></i>
</a>
</form>
<script>
function addCart(id){
$("#form" + id).submit(function(e) {
e.preventDefault();
var code = $(this).find('input[id=code]').val();
var dataString = 'code=' + code;
$.ajax({
type: 'POST',
url: 'addcart.php',
data: dataString,
cache: false,
success: function (result) {
if(result == "success"){
alertify.success("המוצר נוסף לעגלה");
$("#plus").fadeIn(300).delay(1500).fadeOut(300);
}
else{
alertify.error("המוצר כבר קיים בעגלה");
}
}
});
$("#cartreload1").load("product.php #cartreload1");
$("#cartreload2").load("product.php #cartreload2");
$("#cartreload1").load("product.php #cartreload1");
$("#cartreload2").load("product.php #cartreload2");
});
}
</script>
How can I implement submit function inside click function?
P.S. I insist on keeping onclick function in html because its valuable for my php code.
The event inside submit() method occurs when a form is submitted. The form is actually not submitting when you click your button (or link). And note that your button has multiple id attributes. There are several ways to implement it.
1. If your HTML and JS codes are in the same file:
Remove submit() method from addCart() function.
<form method="POST" class="<?php echo $row['code']; ?>" id="form<?php echo $row['id']; ?>">
<a id="submit" class="product-links" href='javascript:addCart(<?php echo $row['id']; ?>);'>
<i class="fa fa-shopping-cart"></i>
</a>
</form>
<script>
function addCart(id) {
var code = $(this).find('input[id=code]').val();
var dataString = 'code=' + code;
$.ajax({
type: 'POST',
url: 'addcart.php',
data: dataString,
cache: false,
success: function (result) {
if(result == "success"){
alertify.success("המוצר נוסף לעגלה");
$("#plus").fadeIn(300).delay(1500).fadeOut(300);
} else {
alertify.error("המוצר כבר קיים בעגלה");
}
}
});
$("#cartreload1").load("product.php #cartreload1");
$("#cartreload2").load("product.php #cartreload2");
$("#cartreload1").load("product.php #cartreload1");
$("#cartreload2").load("product.php #cartreload2");
return false;
}
</script>
2. If your HTML and JS codes are in separate files:
Convert the a element into the button with type="submit" and use data attributes to get the id of the row.
HTML:
<form method="POST" class="<?php echo $row['code']; ?>" id="form<?php echo $row['id']; ?>">
<button id="submit" class="product-links" type="submit" data-id="<?php echo $row['id']; ?>">
<i class="fa fa-shopping-cart"></i>
</button>
</form>
JS:
<script>
$("#form" + id).submit(function(e) {
e.preventDefault();
var code = $(this).data('id');
var dataString = 'code=' + code;
$.ajax({
type: 'POST',
url: 'addcart.php',
data: dataString,
cache: false,
success: function (result) {
if(result == "success"){
alertify.success("המוצר נוסף לעגלה");
$("#plus").fadeIn(300).delay(1500).fadeOut(300);
} else{
alertify.error("המוצר כבר קיים בעגלה");
}
}
});
$("#cartreload1").load("product.php #cartreload1");
$("#cartreload2").load("product.php #cartreload2");
$("#cartreload1").load("product.php #cartreload1");
$("#cartreload2").load("product.php #cartreload2");
});
</script>
If you look closely on .submit() docs you can see that the way you used it is for handling an event. But no event is being triggered. To send the actual event you have to either put data as a first argument and then callback .submit( [eventData ], handler ) or nothing at all .submit().
And now I am wondering what do you actually need to achieve here. If you just want to send AJAX and you can gather the data by yourself, you don't need to use submit event at all. Just remove $("#form" + id).submit(function(e) { and the closing and it should send AJAX on click.
Triggering submit event will result in form being sent ... the old fashion way. Meaning the page will actually go to the url in action attribute - which actually you don't have! You can inject data or hijack the whole submit process with jQuery handler, but I don't think it's what you want to do here.
Related
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}.
well, here my code
From my index.php:
<a href="#" id="save" class="save" onclick='UpdateStatus("<?PHP echo $fgmembersite->UserFullName();?>","<?php echo $_GET['id'] ;?>")'> save</a>
User can save one information when he clicks on this link.
Then, my fuction UpdateStatuts
function UpdateStatus(member1,id1) { //
/* VALUES */
var member = member1;
var id = id1;
var statut = '1';
/* DATASTRING */
var dataString = 'member='+ member+'&id='+ id+'&statut='+ statut;
console.log ("SOMETHING HAPPENS");
$.ajax({
type: "POST",
url: "../../lib/tratement.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
console.log (dataString);
console.log ("AJAX DONE");
}
});
return false;
};
It works perfectly. But after users clicks on the first link, i want to display unsave instead save without reload the whole page.
In an another way, i want this
<a href="#" id="save" class="save" onclick='**RemoveStatus**("<?PHP echo $fgmembersite->UserFullName();?>","<?php echo $_GET['id'] ;?>")'> **Unsave**</a>
instead <a href="#" id="save" class="save" onclick='UpdateStatus("<?PHP echo $fgmembersite->UserFullName();?>","<?php echo $_GET['id'] ;?>")'> save</a>
Is it possible ?
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.
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.
}
why the code below doesn't do its job ?
I just need POST via javascript id content on click btn.
this code works properly in many other situations but not here that i'm using twitter bootstrap modal.
thanks.
<button id="<?php echo $id; ?>" class="btn btn-warning" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<span class="glyphicon glyphicon-trash"></span> delete id
</button>
<script type="text/javascript">
//delete id
$(document).on('click','.btn-warning',function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("are you sure ?")){
$.ajax({
type: "POST",
url: "page.php",
data: info,
success: function(){ window.location.href = "/logout.php"; }
});
}
return false;
});
</script>
PHP
if($_POST['id']){
$id=$_POST['id'];
$id = mysql_real_escape_string($id);
...
info = {'id' : del_id };
Try to send data as array.
First, I think you should be using isset(variable) in the PHP:
if (isset($_POST['ID'])
{
...
Second, it doesn't work because you need to set the data and a key -> value array.
data: {id: "ID_NUMBER"}
Look over the examples on Jquery's site: https://api.jquery.com/jQuery.ajax/
I would also suggest using a unique ID property or a new/unique class proverty, and then using that to add the onClick event.