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}.
Related
For Future Readers, this was my first question and the answer has been found (read comments and replies below):
First of all, i've searched in Stackoverflow and i didn't found an answer for a similar problem.
i would like to link a html Button (among many buttons) with a JQuery function. The function shall execute AJAX method like so :
HTML Code in a separated file index.php:
<button id="submitbtn" type="button" class="btn btn-success">UPDATE</button>
JQuery Function :
$('#submitbtn').on('click', function(){
var id = $(this).data('id');
$.ajax({
url: 'includes/updatequery.php',
type: 'POST',
data: {id:id},
success: function(data){
if (data) {
console.log("updated");
} else {
$('#error').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown){
$('#error').html("oops" + errorThrown);
}
});
});
Here is the PHP file that should be called by AJAX Method :
<?php
include("src/db.php");
$query = "UPDATE mytable SET job='completed' WHERE id=id";
mysqli_query($conn, $query);
?>
The problem is that i CANNOT link the ID of the clicked button (because there are many buttons) to the ID of the Database Entry in order to update the Data in the Database according to this specific button.
Now i would like to have the results updated LIVE after updating the Database.
This is the PHP code that output menu items (items stored in the same Database table as before) and in front of every menu item, a badge should be displayed (with a value within it : "completed" or "not completed") :
<?php
foreach($data as $d) {
$id = $d['id'];
$mystatus = $d['status'];
?>
<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'] == "job") { ?>
<span id="updatedicon" class="right badge <?php if($mystatus == "completed"){echo "badge-success";} else {echo "badge-danger";}?>"><?php setJob($con, $id)?></span><?php
} ?>
</p>
</a>
</li><?php
}
?>
Here is the PHP file where the setJob method is defined :
<?php
function setJob($con, $idd) {
$sql = "SELECT status FROM mytable WHERE id=$id";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
foreach ($row as $row => $value) {
echo $value;
}
}
}
?>
Any suggestions?
Thanks
Use the data-id attribute to add the id:
<button id="submitbtn" data-id="<id>" type="button" class="btn btn-success">UPDATE</button>
https://www.w3schools.com/tags/att_global_data.asp
By default, jQuery ajax uses a Content-Type of application/x-www-form-urlencoded; charset=UTF-8. This means in PHP the POST values can be accessed using $_POST. If using a Content-Type of application/json, you will need to do this.
include("src/db.php");
$id = $_POST['id']; // make sure to sanitize this value
$query = "UPDATE mytable SET job='completed' WHERE id=$id";
mysqli_query($conn, $query);
The above example only demonstrates how to reference the id value from the POST. However, this is not secure as-is. Make sure to sanitize the value as well as protect yourself from SQL Injection using prepared statements. Prepared Statements allow you to bind variables to SQL queries which are sent separately to the database server and can not interfere with the query itself.
Updated HTML - added data-id="" to button and replace with id
<button id="submitbtn" data-id="<id>" type="button" class="btn btn-success">UPDATE</button>
Updated jQuery - use attr to get the id of row/record by using data-id attribute
$('#submitbtn').on('click', function(){
var id = $(this).attr('data-id');
$.ajax({
url: 'includes/updatequery.php',
type: 'POST',
data: {id:id},
success: function(data){
if (data) {
console.log("updated");
} else {
$('#error').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown){
$('#error').html("oops" + errorThrown);
}
});
});
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 been trying to delete a row in my mySQL database on the onclick of a delete button. But instead of the one mySQL row getting deleted, all rows in the database get deleted.
I am targeting just the specific ID, so I am unclear as to why all other ID's are getting deleted.
HTML:
<?php foreach ($movies as $movie) : ?>
<div class="col-4">
<div class="card card-cascade">
<div class="view gradient-card-header purple-gradient">
<h2><?php echo $movie['name']; ?></h2>
<p><?php echo $movie['genre']; ?></p>
</div>
<div class="card-body text-center">
<!-- Delete -->
<a type="button" class="btn-floating btn-small btn-dribbble delbutton" data-toggle="tooltip" data-placement="top" title="Delete" id="<?php echo $movie['id']; ?>"><i class="fa fa-trash-o" aria-hidden="true"></i></a>
</div>
</div>
</div>
<?php endforeach; ?>
JS:
$(function () {
// Tooltips Initialization
$('[data-toggle="tooltip"]').tooltip();
// Delete Movie
$(".delbutton").click(function() {
console.log('watch me')
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "../movieApp/delete.php", //URL to the delete php script
data : {id:info},
success : function() {
console.log("success");
},
error: function () {
console.log("failed");
},
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
PHP:
require 'config/config.php';
require 'config/db.php';
if($_POST['id']){
$id=$_POST['id'];
$delete = "DELETE FROM movies WHERE id=$id";
$result = $conn->query($delete);
}
if (mysqli_query($conn, $sql)) {
mysqli_free_result($result);
mysqli_close($conn);
echo "Worked!";
exit;
} else {
echo "Error deleting record";
}
You set ajax method POST, But Post data format is not correct as per your requirement.
Change your ajax Data like as
//var info = 'id=' + del_id;
var info = {
id : del_id
}
And
$.ajax({
/*...*/
data : info,
/*.../
});
And also check if your id field is string, If integer then change the Query string to -
#$delete = "DELETE FROM movies WHERE id='$id'";
$delete = "DELETE FROM movies WHERE id=$id";
Also change -
#$_POST['info']
$_POST['id']
Because, You didn't set $_POST['info'] anywhere in your code.
Note : And don't forget to console your correct Ajax URL
In your HTML use data-id="<?php echo $movie['id']; ?>" for the tag. Then in your JS you can pick up the value like so: var del_id = $(this).data("id");. I would also inspect element in your browser to see if you are in fact sending an "id" to your PHP script. If you are then possibly you may want to enable error debugging in your PHP script like so: error_reporting(E_ALL);
ini_set('display_errors', 1);. Also wouldn't hurt to change your SQL statement to something like this: $delete = "DELETE FROM movies WHERE id='" . $id . "'";. Good luck with this one doesn't sound too hard.
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'm performing CRUD oprations using JQuery/Ajax and php/MySQL
i'm able to insert/select and delete data but i gotta stuck in edit/update. im pulling data into text box when i click on edit button but after editing when i click on save button unable to update in mysql db!!
Any help is Appreciated Thanks
html code
<span class="noedit name" idl='<?php echo $row->id;?>'>
<?php echo $row->url;?>
</span>
<input id="url1" name="url1" class="form-control edit name url1" value="<?php echo $row->id;?>"/>
<a ide='<?php echo $row->id;?>' id="edit" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
Jquery code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
alert(IdEdit);
$.ajax({
url:"pages/feeds.php",
type:"post",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
$('#id').val(show.id);
$('#url1').val(show.url);
}
});
});
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('error in updating');
}
});
});
PHP Code
if(isset($_POST['editvalue']))
{
$sql = "select * from test where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
if(isset($_POST['update']))
{
$sql = "
update test
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
I don't see an #id input in your code. is it there? I think the problem is here.
If this input exists, use the following tips:
Check if all values (id, url) are sended to your PHP script.
You can use console.log in Javascript or print_r, var_dump functions in PHP.
Change
$('.update').click(function(){
to
$('.saveEdit').click(function(){