JQuery Click handler only works on first item - javascript

With a table I am making I have to make something that will be able to change a value in the database for each row. The problem is that the situation I have right now only affects the tr in the table and not the other tr's.
I am working with Flight (MVC) and this is my code:
The View:
<tbody>
<?php foreach($this->objarrAll as $key => $value){ ?>
<tr>
<td><?= $value['category']; ?></td>
<td><?= $value['user_send']; ?></td>
<td><?= $value['points']; ?></td>
<td><a href="javascript:void(0)" data-toggle="modal"
data-target="#modal-view-<?= $value['id']; ?>">Bekijken</button></td>
<div id="modal-view-<?= $value['id']; ?>" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Inzending van <?= $value['user_send']; ?></h4>
</div>
<div class="modal-body">
<p><img width="868px"
src="#">
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Sluiten</button>
</div>
</div>
</div>
</div>
<input type="hidden" id="uid" value="<?= $value['user_send']; ?>"/>
<input type="hidden" id="points" value="<?= $value['points']; ?>"/>
<input type="hidden" id="row_id" value="<?= $value['id']; ?>"/>
<td><a class="submitPoints" href="javascript:void(0)">Geef punten</a></td>
</tr>
<?php } ?>
</tbody>
The Javascript/AJAX-code:
$(".submitPoints").on("click", function () {
var uid = $('#uid').val();
var points = $('#points').val();
var row_id = $('#row_id').val();
var data = {
uid: uid,
points: points,
row_id: row_id
};
$.ajax({
type: "POST",
url: "/update/user/points",
async: true,
data: data,
success: function (data) {
console.log("De " + points + " punten zijn toegekend aan " + uid + "");
var err = jQuery.parseJSON(data);
sendAlert.createAlert(err.return, err.type);
$("#check-view").load("/admin/table/check/all", function () {
});
}
});
});
The Model and Controller are working fine, because the SQL query is being executed.

First change your ids to classes
<input type="hidden" class="uid" value="<?= $value['user_send']; ?>"/>
<input type="hidden" class="points" value="<?= $value['points']; ?>"/>
<input type="hidden" class="row_id" value="<?= $value['id']; ?>"/>
Second put a class on your tr
<tr class="row">
Then change your binding to be a contextual lookup.
$(".submitPoints").on("click", function (e) {
var $row = $(e.target).closest('.row');
var uid = $row.find('.uid').val();
var points = $row.find('.points').val();
var row_id = $row.find('.row_id').val();
OPTIONALLY, you could use data elements, and forget about hidden fields all together.
<td><a class="submitPoints" href="javascript:void(0)" data-uid="<?= $value['user_send']; ?>" data-points="<?= $value['points']; ?>" data-rowid="<?= $value['id']; ?>">Geef punten</a></td>
In which case your event handler would just be...
$(".submitPoints").on("click", function (e) {
var $submit = $(e.target);
var uid = $submit.data('uid');
var points = $submit.data('points');
var row_id = $submit.data('rowid');

I'm sure the click handler is working on all elements, this is the problem:
var uid = $('#uid').val();
var points = $('#points').val();
var row_id = $('#row_id').val();
id attributes need to be unique, when you refer to them in this way it will return the first one found in the DOM. You could try changing to:
var uid = $(this).find('#uid').val();
var points = $(this).find('#points').val();
var row_id = $(this).find('#row_id').val();
But it would be better to switch to class instead of id
var uid = $(this).find('.uid').val();
var points = $(this).('.points').val();
var row_id = $(this).find('.row_id').val();

<input type="hidden" id="uid_<?php echo $value['id']; ?>" value="<?= $value['user_send']; ?>"/>
<input type="hidden" id="points_<?php echo $value['id']; ?>" value="<?= $value['points']; ?>"/>
<input type="hidden" id="row_id_<?php echo $value['id']; ?>" value="<?= $value['id']; ?>"/>
<td><a class="submitPoints" href="ajax_call('uid_<?php echo $value['id']; ?>','points_<?php echo $value['id']; ?>','row_id_<?php echo $value['id']; ?>')">Geef punten</a></td>
<script>
function ajax_call(id_1,id_2,id_3)
{
var uid = $('#'+id_1).val();
var points = $('#'+id_2).val();
var row_id = $('#'+id_3).val();
var data = {
uid: uid,
points: points,
row_id: row_id
};
$.ajax({
type: "POST",
url: "/update/user/points",
async: true,
data: data,
success: function (data) {
console.log("De " + points + " punten zijn toegekend aan " + uid + "");
var err = jQuery.parseJSON(data);
sendAlert.createAlert(err.return, err.type);
$("#check-view").load("/admin/table/check/all", function () {
});
}
});
}
</script>

Related

How can I update any row rather than only the top row with the update button on each side in PHP and AJAX

just starting out so gonna sound like a noob question but how can I use the update button to update individual rows rather than only the top row.
Whenever I use the update button, the request only goes through if it was the top row.
This is the code for the index.php
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<center>
<h3>UPDATE DATA</h3>
<?php
$run = 0;
$conn = new mysqli('localhost', '', '', '');
$sql = "SELECT * FROM moderator";
$result = $conn->query($sql);
while ( $row=mysqli_fetch_assoc($result)) {
$run = $run + 1;
?>
<div>
ID<input type="text" id="id" value="<?php echo $row['id']; ?>">;
Moderator<input type="text" id="mod" value="<?php echo $row['name']; ?>">;
Category<input type="text" id="ctgr" value="<?php echo $row['category']; ?>">;
<button type="submit" id="update" rel="<?php echo $run; ?>">UPDATE</button>
</div>
<?php
}?>
</center>
<script>
$(document).ready(function(){
$("#update").click(function(){
var name=$("#mod").val();
var ctgr=$("#ctgr").val();
var id=$("#id").val();
$.ajax({
url:'update.php',
method:'POST',
data:{
name:name,
ctgr:ctgr,
id:id
},
success:function(response){
alert(response);
}
});
});
});
</script>
</body>
This is the code for the update.php
<?php
$conn = new mysqli('localhost', '', '', '');
$name=$_POST["name"];
$ctgr=$_POST["ctgr"];
$id=$_POST["id"];
$sql="UPDATE moderator set name='$name', category='$ctgr' where id='$id'";
if($conn->query($sql)===TRUE){
echo "DATA updated";
}
?>
You can probably see I'm trying to create an individual variable for each row but I can't figure it out. Sorry, code's very messy too.
I've removed datebase information but the rows display when credentials are inserted.
This is because you have duplicated input ids, you should have only one ID with the same value on html, this is valid some how, you don't get an error, but you will have trouble in javascript when you try to access those id, you will get only the first one.
To fix this you can remove id and put it as class:
<div>
ID<input type="text" class="id" value="<?php echo $row['id']; ?>">;
Moderator<input type="text" class="mod" value="<?php echo $row['name']; ?>">;
Category<input type="text" class="ctgr" value="<?php echo $row['category']; ?>">;
<button type="submit" class="update" rel="<?php echo $run; ?>">UPDATE</button>
</div>
and use this JS:
$(document).ready(function(){
$(".update").click(function(){
var container = $(this).closest('div'); // parent div
var name = container.find('.mod').val();
var ctgr = container.find('.ctgr').val();
var id = container.find('.id').val();
$.ajax({
url:'update.php',
method:'POST',
data:{
name:name,
ctgr:ctgr,
id:id
},
success:function(response){
alert(response);
}
});
});
});
All your rows input elements have same id attribute
Like id of first rows elements are like id, mod, ctgr
Also id of second rows elements are id, mod ctgr
Jquery find first element, if multiple elements of same id there
You can make unique id by apppending a uniqe incremental variable $run to it as
ID<input type="text" id="id"+<?php echo $run; ?> value="<?php echo $row['id']; ?>">; Moderator<input type="text" id="mod"+<?php echo $run; ?> value="<?php echo $row['name']; ?>">; Category<input type="text" id="ctgr"+<?php echo $run; ?> value="<?php echo $row['category']; ?>">; <button type="submit" id="update" rel="<?php echo $run; ?>" onclick="updatetodb( <?php echo $run; ?>);“ >UPDATE</button>
Then create a javascript function with name updatetodb with one argument, and identify row by that argument as
function updatetodb(var run) {
var id=$('#id' +run).value;

update modal bootstrap and ajax

-when i update with ajax , he changed but he only took to 'id' not the new variable
But I want to insert my E-Mail to database through Ajax. I don't want my page to get redirected, because every time the page got refreshed, null value got inserted to the database..
1)and ajax
function editdata(str){
var id= str;
var name = $('#nameofequipe-'+str).val();
$.ajax({
type:"post",
url: "<?php echo API;?>equipe/update.php",
data:"nameofequipe="+name+"&id="+id,
success:function(data){
alert('success update data ');}
2)and modal bootstrap
<div
class="modal fade"
id="edit-<?php echo $row['id']; ?>"
role="dialog"
aria-labelledby="updatelLabel-<?php echo $row['id']; ?>
<input
type="hidden"
id="<?php echo $row['id']; ?>"
value="<?php echo $row['id']; ?>" >
<input
type="text"
class="form-control"
id="nameofequipe-<?php echo $row['id']; ?>"
value="<?php echo $row['equipe']; ?>">
if somoene know how i can do This can He help me
//use this in script section
function editdata(str){
var id= str;
var name = $('#nameofequipe-'+str).val();
$.ajax({
dataType: "json",
type:"post",
url: "<?php echo API;?>equipe/update.php",
data:"{nameofequipe:"+name+",id:"+id+"}",
success:function(data){
alert('success update data ');
}
//whereas this one in your PHP file where you use this data nameOfEquipe and Id to update you database.
if(isset($_POST['nameofequipe'], $_POST['id']) {
$nameOfEquip=$_POST['nameofequipe'];
$id=$_POST['id'];
}
This Is all code
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
</button>
</div>
<form>
<div class="modal-body">
<input type="hidden" id="<?php echo $row['id']; ?>" value="<?php echo $row['id']; ?>" >
<input type="text" class="form-control" name="nameofequipe-<?php echo $row['id']; ?>" value="<?php echo $row['equipe']; ?>">
</div>
<button type="submit" onclick='editdata(<?php echo $row['id']; ?>)' class="btn btn-primary">Save changes</button>
</div>
</form>
ajax and js
function editdata(str)
{
var id= str;
var name= $('#nameofequipe-'+str).val();
$.ajax ({
type:"post",
url: "<?php echo API;?>equipe/update.php",
data:"nameofequipe="+name+"&id="+id,
success: function(data){
alert("Data Save: " + data);
}
}); }
update. PHP
$id = $_POST['id'];
$name=$_POST['nameofequipe'];
$result = $o->SelectQuery("UPDATE rh_equipes SET equipe='$name' WHERE id='$id'");
if($result){
echo 'data update';
}

How to get foreach input value in javascript and pass it to ajax data?

This is my Form
<form method="post" id="BargainForm">
<input type="hidden" name="pro_id" class="pro_id" id="pro_id" value="<?php echo $pro_id; ?>">
<input type="hidden" name="customer_id" class="customer_id" id="customer_id" value="<?php echo $customer_id; ?>">
<input type="text" name="bargain_qty" class="bargain_qty" id="bargain_qty" placeholder="Qty" required/></br></br>
<?php if($productType = 'Configurable'): ?>
<?php foreach($attributes as $attribute): ?>
<input type="text" name="<?php echo strtolower($attribute['store_label']); ?>"
class="<?php echo strtolower($attribute['store_label']); ?>"
id="<?php echo strtolower($attribute['store_label']); ?>"
placeholder="<?php echo $attribute['store_label'] ?>"></br></br>
<?php endforeach; ?>
<?php else: ?>
<?php endif; ?>
<input type="text" name="bargain_price" class="bargain_price" id="bargain_price" placeholder="Total Price" required/></br></br>
<input type="submit" name="bargain_btn" class="bargain_btn">
</form>
Here is my javascript code
<script type="text/javascript">
$(function () {
$('.bargain_btn').click(function(e) {
var qty = $( "#bargain_qty" ).val();
var price = $( "#bargain_price" ).val();
var pro_id = $( "#pro_id" ).val();
var customer_id = $( "#customer_id" ).val();
var att_lable = $( "#<?php echo strtolower($attribute['store_label']); ?>" ).val();
alert(att_lable);
e.preventDefault();
$.ajax({
url: "<?php echo Mage::getUrl('bargain/Ajax/index'); ?>",
type: "POST",
data: {qty,price,pro_id,customer_id},
success: function(data) {
if(data.success) {
}
}
});
});
});
In form i am using foreach. If i have 2 data so it will display 2 input tags, i just don't know how to save values of that 2 input and pass it to data: {qty,price,pro_id,customer_id},
Thank you in advance!
Provide a common class to all textbox that are generated using loop like:
foreach(...)
{
echo '<input class="myTxt" value="" id="" />';
}
Jquery:
var arr = [];
$('.myTxt').each(function(){
arr.push($(this).val());
});
pass this array i.e. arr to ajax call in data{} section using serialize or on an index.
Replace
data: {qty,price,pro_id,customer_id},
By
data: "qty="+qty+"&price="+price+"&pro_id="+pro_id+"&customer_id="+customer_id+"&att_lable="+att_lable,
Do not use:
data: { qty, price, pro_id, customer_id },
Instead use:
data: $("#BargainForm").serialize(),
It will work only if your $attribute['store_label'] name is unique.

div id refresh on ajax success

I have a div at index.php which i want to refresh as the ajax call succeeds. I tried this. But it is not refreshing the div unless i refresh the whole page.
here is the code.
Div
<div id="cartContainer">
<div id="cart">
<li style="color: #515151">
<img id="cart_img" src="images/cart.png"> Cart <span class='badge' id='comparison-count'>
<?php
if(isset($_SESSION['cart'])&& !empty($_SESSION['cart']))
{
$cart_count=count($_SESSION['cart']);
echo $cart_count;
} else {
$cart_count=0;
echo $cart_count;
}
?>
</span>
</li>
<div id="sidebar">
<?php if(isset($_SESSION[ 'cart'])&& !empty($_SESSION[ 'cart'])){ ?>
<table id="s_table">
<?php foreach($_SESSION[ 'cart'] as $id=> $value){ ?>
<form class="product" method="get" action="index.php?">
<tr id="tr_s">
<input type="hidden" name="action" value="remove">
<input type="hidden" name="id" value="<?php echo $value['id'] ?>">
<td class="s_th">
<?php echo $value[ 'name']; ?>
<input type="hidden" name="name" value="<?php echo $value['name'] ?>">
</td>
<td class="s_th">
<?php echo $value[ 'quantity'] ?>
<input type="hidden" name="quantity" value="<?php echo $value['quantity'] ?>">
</td>
<td class="s_th">
<?php echo $value[ 'color']; ?>
<input type="hidden" name="color" value="<?php echo $value['color'] ?>">
</td>
<td class="s_th">
<?php echo $value[ 'size'] ?>
<input type="hidden" name="size" value="<?php echo $value['size'] ?>">
</td>
<td>
<button type="submit" id="btn_submit">Remove</button>
</td>
</tr>
</form>
<?php } ?>
<tr>
<td class="cart_btn" colspan="2">GO TO CART
</td>
<td class="cart_btn" colspan="2">CHECK OUT
</td>
</tr>
</table>
<?php } else { ?>
<p id="p_s"><i> "Your Cart is Empty"</i>
</p>
<?php } ?>
</div>
</div>
</div>
Ajax
<script>
$(document).ready(function() {
$('#addtocart').click(function(e) {
e.preventDefault();
var page = $("#page").val(),
action = $("#action").val(),
name = $("#name").val(),
id = $("#id").val(),
color = $("#color").val(),
size = $("#size").val(),
cat_id = $("#cat_id").val(),
s_cat_id = $("#s_cat_id").val(),
category = $("#category").val();
var proceed = true;
if (proceed) {
post_data = {
'Page': page,
'Action': action,
'Name': name,
'Cat_id': cat_id,
'S_cat_id': s_cat_id,
'Category': category,
'Id': id,
'Color': color,
'Size': size
};
$.post('add_cart.php', post_data, function(response) {
//load json data from server and output message
if (response.type == 'error') {
//output=$('.alert-error').html(response.text);
} else {
output = $("#cartContainer").load();
}
$(".alert-error").delay(3200).fadeOut(300);
}, 'json');
}
});
});
</script>
If you want to update the div with the return from you AJAX you would do something like this:
$.post('add_cart.php', post_data, function(response) {
$("#cartContainer").html(response);
}
Of course this depends on many things: the kind of data you're returning, what you wish to update, etc. It is hard to tell, from what you have posted, what your intent is.

Delete row in html table with checkbox using php and ajax

I need delete each row in html table using checkbox
Currently can delete row using link
I am using switch in my code in case delete query exist
Code php
<tr class="<?php if($i%2 == 0) { echo 'even'; } else { echo 'odd'; }
?>">
<td><div class="grid_content sno"><span><?php echo $i; ?>
</span> </div></td>
<td><div class="grid_content editable"><span><?php echo
$records['name_ar']; ?></span><input type="text"
class="gridder_input"
name="<?php echo encrypt("name_ar|".$records['id']); ?>"
value="<?php echo $records['name_ar']; ?>" /></div></td>
<td><div class="grid_content editable"><span>
<?php echo $records['name_en']; ?>
</span><input type="text" class="gridder_input"
name="<?php echo encrypt("name_en|".$records['id']); ?>"
value="<?php echo $records['name_en']; ?>" /></div></td>
<td>
<a href="<?php echo encrypt($records['id']); ?>"
class="gridder_delete"><img src="images/delete.png"
alt="Delete" title="Delete" /></a>
<input type="checkbox" name="delete[]"
value="<?php echo encrypt($records['id']); ?>" />
</td>
</tr>
case "delete":
$value = decrypt($_POST['value']);
$query = mssql_query("DELETE FROM Job_creation WHERE id = '$value' ");
break;
code ajax
// Function for delete the record
$('body').delegate('.gridder_delete', 'click', function(){
var conf = confirm('Are you sure want to delete this record?');
if(!conf) {
return false;
}
var ThisElement = $(this);
var UrlToPass = 'action=delete&value='+ThisElement.attr('href');
$.ajax({
url : 'ajax.php',
type : 'POST',
data : UrlToPass,
success: function() {
LoadGrid();
}
});
return false;
});
Many thanks in advance for those who help me :)

Categories