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 ?
Related
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.
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.
}
I am using AJAX to send data to server and update the current page with no reloading. I have this script:
$.ajax
({
url: 'insert.php',
type: 'POST',
data: {data1: emp, data2: pos, data3: sal},
dataType: "json",
success:function(data)
{
var emp_n = data.emp_name;
var btn = '<button type="Button" id="del" name="del" class="btn btn-danger">Delete</button></a>';
$("#before_tr").before("<tr><td>"+data.emp_name+"</td><td>"+data.position+"</td><td>"+data.salary+"</td><td>"+btn+"</td></tr>");
},
As you see, I have a delete button that should be added too to the same row. But this button won't be active until I refresh the page. What I want is to append action like this PHP Based code for a delete button of each row:
<tr id="<?php echo $row['id']; ?>">
<td contenteditable><?php echo $row['emp_name'] ?></td>
<td contenteditable><?php echo $row['position'] ?></td>
<td contenteditable><?php echo $row['salary'] ?></td>
<td><button type="Button" id="del" name="del" class="btn btn-danger">Delete</button>
</tr>
<?php } ?>
What I've tried is the following:
$.ajax
({
url: 'insert_with_ajax.php', //Sending variable emp, pos, and sal, into this url
type: 'POST', //I will get variable and use them inside my PHP code using $_POST['emp']
data: {data1: emp, data2: pos, data3: sal},//Now we can use $_POST[data1];
dataType: "json", //JSON or HTML
success:function(arr)
{
//if(data=="success")
//{
//alert("Data added");
var emp_n = arr.emp_name;
var btn = 'Delete</button>';
$("#before_tr").before("<tr><td>"+arr.emp_name+"</td><td>"+arr.position+"</td><td>"+arr.salary+"</td><td>"+btn+"</td></tr>");
$("#emp_name").val("");
$("#position").val("");
$("#salary").val("");
//}
},
Where I added this line <a href="delete_id.php?id="'+emp_n+' to the following:
var btn = 'Delete</button>';
When I click on delete button of the last one added using AJAX the page go to delete_id but the link is like this:
delete_id.php?id=
id is equal to empty.
So, What I am working on is like when we add a status on Facebook and you delete it directly with no need for reloading the page. I am trying and I hope that someone could help.
Check your code once again:
'<a href="delete_id.php?id="'+emp_n+'>'
^ - see? you have a closing " here.
This means that no values will be added to your href attribute as it's already closed.
Proper code is:
'<a href="delete_id.php?id='+emp_n+'">'
^ -see? closing " moved after emp_n
I have created an AJAX that can store and delete data from database. The adding of data is working fine also the delete function is working fine when the page is already refresh but the delete is not working when data is newly added or when the page is not refresh.
This how it works. When a new data is added, the data will display, the user has an option to delete the data or not. The data has a "X" to determine that it is a delete button. Right now, The delete only works when the page is refresh.
This my SAVING script, as you can see if saving is success it displays the data automatically, together with the span that has the delete function.
$("#wordlistsave").click(function()
{
var user = $("#getUser").val();
var title = $("#wordbanktitle").val();
var words = $("#wordbanklist").val();
var postID = $("#getPostID").val();
var ctrtest = 2;
var testBoxDiv = $(document.createElement('div'))
.attr("id", words);
var dataString = 'user='+user+'&title='+title+'&words='+words+'&id='+postID;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(postID)
{
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+words+'" style="cursor:pointer">x '+postID+'</span>  <input type="checkbox" name="words[]" value="'+ words+ '">'+words );
testBoxDiv.appendTo("#test_container");
ctrtest++;
}
});
<?php else: ?>
alert('Fail.');
<?php endif; ?>
});
This is my delete function , when the user click the "X" span, the data will be deleted, but this only works after the page is refresh.
$("span").click(function()
{
var queryword=$(this).attr('id');
var postIDdel = $("#getPostID").val();
var dataString = 'queryword='+queryword+'&postID1='+postIDdel;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('worddelete.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(html)
{
$('div[id="'+queryword+'"]').remove();
}
});
<?php else: ?>
<?php endif; ?>
});
This is my HTML, the one that holds the querying of data and displaying of data.
<?php
global $wpdb;
$query_wordbanklist = $wpdb->get_results("SELECT meta_value, meta_id FROM wp_postmeta WHERE post_id = '$query_id' AND meta_key = '_wordbanklist'");
if($query_wordbanklist != null)
{
echo "<h3> Wordlist </h3>";
foreach($query_wordbanklist as $gw)
{
?> <div id="<?php echo $gw->meta_value ?>">
<span id="<?php echo $gw->meta_value ?>" style="cursor:pointer">x</span>   <input type="checkbox" name="words[]" value="<?php echo $gw->meta_value ?>"><?php echo $gw->meta_value; ?>
</div>
<?php
}
}
?>
All I wanted to achieve is to make the delete function works right after the data is stored. Right now it only works when the page is refresh. Any idea on this?
Perhaps try this...
$(document).on('click', 'span', function() {
// delete stuff in here
}
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.