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.
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}.
I am updating a span using below script but it is working if condition is false and if condition is true it does not update.
What i observed that it executes the same false condition and when i click the second time it updates the quantity but less 1 number than the actual quantity of records in the database.
Like total records are 2 and when i click submit the script runs and if condition is true in the database records are updated = 3 but in the span it shows 2.
When i click 2nd time and in the database records are = 4 and in the span it shows 3.
Button where i click and run the script
<input onclick='updateTitems("1");' type="submit" class="btn-style-2 mg-left-5" value="ADD TO CART">
script
<script>
function updateTitems(id) {
var uid = "<?php echo $ses_mem; ?>";
$.ajax({
type: "GET",
url: 'inc/menu_update_total_items.php',
data: "id=" + id + "&uid=" + uid,
success: function(data) {
$('.summary12').html(data);
}
});
}
</script>
menu_update_total_items.php
$user_id = $_GET['uid'];
$item = "select count(*) as records
from orders_temp
where user_id = '".$user_id."'
";
$itemq = $dba->query($item);
$itemr = $itemq->fetch_assoc();
$count = $itemr['records'];
---------------------------------
$itemx = "select count(*) as records
from orders_temp
where date = now()
and user_id = '".$user_id."'
";
$itemqx = $dba->query($itemx);
$itemrx = $itemqx->fetch_assoc();
$check = $itemrx['records'];
<span class="summary12"><!-- class of javascript -->
<?php
if ($check == 1){
echo $count+1;
}else{
echo $count;
}
?>
Items
</span>
After trying lot of things i came up with the following solution and the issue has been solved.
Please need your opinion on this. Thanks
Button
<input onclick='updateTitems();' type="submit" class="btn-style-2 mg-left-5" value="ADD TO CART">
Script
function updateTitems(){
$.ajax({
url: "menu_update_total_items.php",
cache: false,
success: function(data){
$(".summary12").html(data);
//div or span reload script after success
setInterval(function () {
$('.summary12').load('inc/menu_update_total_items.php');
}, 1000);
}
});
}
menu_update_total_items.php
<?php
#session_start();
include ("inc/db.php");
$ses_mem = session_id();
$items = "select count(*) as trecords
from orders_temp
where user_id = '".$ses_mem."' ";
$item = $dba->query($items);
$count = $toitemszx->fetch_assoc();
?>
<a href="cart/review" class="cart-link">
<i class="fa fa-shopping-basket"></i>
<?php echo $count['trecords']; ?>
Items
</a>
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'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(){
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
}