I am using jquery to print the following table. Table has two columns. one for the values and other for the check boxes.
Problem I am facing is when I click a checkbox, it is triggering the function which is supposed to be triggered only when the value clicked.
Can somebody tell me how to stop triggering the function when a check box is clicked?
PHP code that prints the table
<table border='1' cellspacing='12' cellpadding='4' style='border-collapse: collapse' width='700' id=topictable >
<?php while ($row = mysql_fetch_assoc($results)) {
$topic = $row['topic'];
?>
<tr bgcolor='white'>
<td class='value'><a href='#'><?php $topic ?></a></td>
<td bgcolor='white'width='5%'><input type=checkbox name=chekboxTopic[] value= <?php $topic ?> </td>
</tr>
<?php
}
?>
</table>
Java script
$(document).on("click","#topictable td", function() {
// to set the session variable`enter code here`
var strSelectedTopic = ($( this ).text());
alert(strSelectedTopic);
var switchval = "setsessiontopic";
var param = "switchval=" + switchval + "&topic=" + strSelectedTopic;
ajaxSend(param);
var form = document.getElementById("abcd");
form.action = "design.php"
form.target = "_blank";
form.submit();
return false;
});
Couple things.
Close off your inputs
Change what is supposed to be clicked; make it more specific
Demo: http://jsfiddle.net/dL3s3acn/
<table border='1' cellspacing='12' cellpadding='4' style='border-collapse: collapse' width='700' id=topictable >
<?php
while ($row = mysql_fetch_assoc($results)) {
$topic = $row['topic'];
?>
<tr bgcolor='white'>
<td class="value"><?php $topic ?></td>
<td bgcolor="white" width="5%"><input type="checkbox" name="chekboxTopic[]" value="<?php $topic ?>" /></td>
</tr>
<?php
}
?>
</table>
<script>
// Click on the class ".value" not "td", that is too broad
$(document).on("click","#topictable .value", function() {
// to set the session variable`enter code here`
var strSelectedTopic = ($(this).text());
alert(strSelectedTopic);
var switchval = "setsessiontopic";
var param = "switchval="+switchval+"&topic="+strSelectedTopic;
ajaxSend(param);
var form = document.getElementById("abcd");
form.action = "design.php"
form.target = "_blank";
form.submit();
return false;
});
</script>
Related
I'm currently building a form, and using a PHP loop to build the elements in a table which hold the values I'm submitting after clicking a checkbox.
<form id="saveLineup">
#foreach($lists as $list)
<tr style="text-align:center;">
<td id="groupNumber">{{$list['product']}} - {{$list['product_NAME']}}</td>
<td id="detailColor">{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}</td>
<td id="category">{{$list['CATEGORY']}}</td>
<td><input id="addToLineup"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?>></td>
</tr>
#endforeach
</form>
My issue is, I have an id on the checkbox and id's on the values so I can only get the console log when I click the very first checkbox and it only logs the very first item. How can I change this so that I can submit with any checkbox in the table and it's associated values?
$("#addToLineup").click(function (e) {
var productNumber = document.getElementById("productNumber").innerHTML = productNumber;
var detailColor = document.getElementById("detailColor").innerHTML = detailColor;
var category = document.getElementById("category").innerHTML = category;
updatedata.productNumber = productNumber;
updatedata.detailColor = detailColor;
updatedata.category = category;
$.ajax({
url: "/test/addToLineup",
data: updatedata,
_token: phpVariables.csrfToken,
type: "POST",
beforeSend: function () {
showLoading(element);
},
success: function (data) {
location.reload();
},
});
});
Here is the solution to your problem, you need to use classes instead of IDs.
#foreach($lists as $list)
<tr style="text-align:center;">
<td class="groupNumber">{{$list['product']}} - {{$list['product_NAME']}}</td>
<td class="detailColor">{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}</td>
<td class="category">{{$list['CATEGORY']}}</td>
<td><input class="addToLineup"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?>></td>
</tr>
#endforeach
Now, in your JS section, you can fetch them by their class:
var productNumber = document.getElementsByClassName("productNumber").innerHTML = productNumber;
var detailColor = document.getElementsByClassName("detailColor").innerHTML = detailColor;
var category = document.getElementsByClassName("category").innerHTML = category;
Note: If you're applying CSS styles to those elements via their ID, you can change #productNumber to .productNumber in your CSS or you can leave the ID tag with the same name as your previous code.
In PHP code
<form id="saveLineup">
<?php $i=0; ?>
#foreach($lists as $list)
<?php $i+=1; ?>
<tr style="text-align:center;">
<td id="groupNumber<?php echo $i ?>">.
{{$list['product']}} - {{$list['product_NAME']}}
</td>
<td id="detailColor<?php echo $i ?>">.
{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}.
</td>
<td id="category<?php echo $i ?>">.
{{$list['CATEGORY']}}
</td>
<td>
<input id="addToLineup<?php echo $i ?>"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo
"checked='checked'"; ?>>
</td>
</tr>
#endforeach
<input id="listcount"> type="hidden" value="<?php echo $i; ?>" >
</form>
Js function
$("#addToLineup").click(function (e) {
for(var i=1 ; i <= parseInt(document.getElementById("listcount").value); i++) {
Console.log(document.getElementById("productNumber"+i).innerHTML);
Console.log(document.getElementById("detailColor"+i).innerHTML);
Console.log(document.getElementById("category"+i).innerHTML);
}
});
I have a strange problem here. I am processing data via AJAX from a table loaded inside while loop and when the data is successfully processed the table gets reloaded with new data via AJAX and JSON. The problem is that when the new table is loaded and I click the same submit button from any row again then this time instead of processing it via AJAX it works as a normal submit button and refreshes the page. Then when the page is refreshed the submit button works via AJAX again. Why is it not working with AJAX when the table was reloaded via AJAX after previous operation via AJAX when in both the tables the parameters used are exactly the same? My codes are below. Please tell my what's wrong here and what's the solution for this.
membership.php
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Memberships List</h3>
</div>
<div class="card-body table-responsive p-0">
<table class="table table-hover table-striped" id="mbslist">
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php
$i = 1;
$mem = $pdo->prepare("SELECT * FROM memberships");
$mem-> execute();
while($m = $mem->fetch()){ extract($m);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
?>
<tr>
<td><?php echo $i; ?></td>
<td><span style="color: <?php echo $mem_color; ?>"><?php echo $mem_name; ?></span></td>
<td>₹<?php echo $mem_daily_capping; ?></td>
<td>₹<?php echo $mem_earn_amount; ?></td>
<td>₹<?php echo $mem_min_payout; ?></td>
<td><?php echo $mem_payout_percent; ?>%</td>
<td><?php if($mem_price == '0.00'){ echo "Free"; }else{ echo "₹$mem_price"; } ?></td>
<td><span class="<?php echo $statusColor; ?>"><?php echo ucfirst($mem_status); ?></span></td>
<td>
<form method="post" action="">
<input type="hidden" value="<?php echo $mem_id; ?>" class="memid">
<input type="hidden" value="<?php echo $status; ?>" class="status">
<input type="hidden" value="memstatus" class="type">
<?php if($mem_id != 1){ ?>
<input type="submit" class="btn <?php echo $btn; ?> mbslist" value="<?php echo ucfirst($btnVal); ?>">
<?php } ?>
Edit
</form>
</td>
</tr>
<?php $i++; } ?>
</table>
</div>
</div>
</div>
<div class="message"></div>
</div>
AJAX Code
// Set Membership Status
$(document).ready(function(){
$(".mbslist").click(function() {
var dataString = {
id: $(this).closest('tr').find('.memid').val(),
type: $(this).closest('tr').find('.type').val(),
status: $(this).closest('tr').find('.status').val()
};
console.log(dataString);
$.ajax({
type: "POST",
dataType : "json",
url: "processes/memberships.php",
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$('.overlay').fadeIn();
},
success: function(json){
$('.message').html(json.status);
setTimeout(function(){
$('.overlay').fadeOut();
$('.message').fadeIn();
$('#mbslist').html(json.table).fadeIn();
}, 2000);
}
});
return false;
});
});
processes/memberships.php
<?php
include('../../config/db.php'); include('../../functions.php');
$memid = (!empty($_POST['id']))?$_POST['id']:null;
$type = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;
$color = (!empty($_POST['color']))?$_POST['color']:null;
$name = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price = (!empty($_POST['price']))?$_POST['price']:null;
if($_POST){
if($type == 'memstatus'){
$update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
$update-> bindValue(':status', $status);
$update-> bindValue(':id', $memid);
$update-> execute();
if($update){
$pro = $pdo->prepare("SELECT * FROM memberships");
$pro-> execute();
$table = "<table class='table table-hover table-striped' id='mbslist'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>";
$i = 1;
while($p = $pro->fetch()){ extract($p);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
$table .= "<tr>
<td>".$i."</td>
<td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
<td>₹".$mem_daily_capping."</td>
<td>₹".$mem_earn_amount."</td>
<td>₹".$mem_min_payout."</td>
<td>".$mem_payout_percent."%</td>
<td>".$mp."</td>
<td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
<td>
<form method='post' action=''>
<input type='hidden' value=".$mem_id." class='memid'>
<input type='hidden' value=".$status." class='status'>
<input type='hidden' value='memstatus' class='type'>
<input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
<a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
</form>
</td>
</tr>";
$i++;
}
$table .= "</table>";
echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
}else{
echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
}
}
}
Modify your processes/memberships.php with following code:
$memid = (!empty($_POST['id']))?$_POST['id']:null;
$type = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;
$color = (!empty($_POST['color']))?$_POST['color']:null;
$name = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price = (!empty($_POST['price']))?$_POST['price']:null;
if($_POST){
if($type == 'memstatus'){
$update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
$update-> bindValue(':status', $status);
$update-> bindValue(':id', $memid);
$update-> execute();
if($update){
$pro = $pdo->prepare("SELECT * FROM memberships");
$pro-> execute();
$table = "<table class='table table-hover table-striped' id='mbslist'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>";
$i = 1;
while($p = $pro->fetch()){ extract($p);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
$table .= "<tr>
<td>".$i."</td>
<td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
<td>₹".$mem_daily_capping."</td>
<td>₹".$mem_earn_amount."</td>
<td>₹".$mem_min_payout."</td>
<td>".$mem_payout_percent."%</td>
<td>".$mp."</td>
<td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
<td>
<form method='post' action=''>
<input type='hidden' value=".$mem_id." class='memid'>
<input type='hidden' value=".$status." class='status'>
<input type='hidden' value='memstatus' class='type'>
<input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
<a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
</form>
</td>
</tr>";
$i++;
}
$table .= "</table>";
echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
}else{
echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
}
}
}
?>
<script>
// Set Membership Status
$(document).ready(function(){
$(".mbslist").click(function() {
var dataString = {
id: $(this).closest('tr').find('.memid').val(),
type: $(this).closest('tr').find('.type').val(),
status: $(this).closest('tr').find('.status').val()
};
console.log(dataString);
$.ajax({
type: "POST",
dataType : "json",
url: "processes/memberships.php",
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$('.overlay').fadeIn();
},
success: function(json){
$('.message').html(json.status);
setTimeout(function(){
$('.overlay').fadeOut();
$('.message').fadeIn();
$('#mbslist').html(json.table).fadeIn();
}, 2000);
}
});
return false;
});
});
</script>
Hope this might help you.
Your submit button will try to submit form normally when you click it. So just use "event.preventDefault() " as below so your button wont trigger normal form submission and now wont load the page.
$(".mbslist").click(function(event) {
event.preventDefault();
}
I am trying to print the elements of an array in PHP which was passed from Javascript. I think the js array is being passed but for some reason it is not being printed via php. Sorry if my code is not properly indented. TIA
<?php
$link = mysqli_connect("localhost","xxxx", "xxxxxx","xxxx");
if($_POST['delete']){
$delete= json_decode($_POST['str'], true);
foreach($delete as $x){
echo"<script> alert(".$x.");</script>";
}
}
?>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body >
//This is a table which displays rows from a database.
//The user selects rows and the ids of those rows are
//are stored in a javascript array called 'toDelete'
//I want to pass this array to PHP
<form method="post" id="myForm" >
<table id="secondDiv" >
<tr>
<th >
<form><input class="checkbox"type="checkbox" name="selectAll" id="selecctall" value=""></form>
</th>
<th>Date</th>
<th>Event</th>
<th>Details</th>
<th>Time & Location</th>
</tr>
<?php
$link = mysqli_connect("localhost","xxxx", "xxxxxx","xxxx");
$query = "SELECT * FROM meetings";
if($result = mysqli_query($link,$query)){
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td><form ><input class=\"checkbox1\" type=\"checkbox\" name=\"".$row['meetingNo']."\" >
</form></td>";
echo "<td>".$row['date']."</td>";
echo "<td>".$row['event']."</td>";
echo "<td>".$row['details']."</td>";
echo "<td>".$row['location']."</td>";
echo "</tr>";
}
}
?>
</table>
<!-- <input type="submit" class="btn btn-warning" value="Edit" /> -->
<input type="hidden" id="str" name="str" value="" />
<input type="submit" id="btn" name="delete" value="Delete" />
</form>
<script>
var toDelete = new Array();
$(document).ready(function() {
$('#selecctall').click(function(event) { //on click
if(this.checked) { // check select status
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkbox1"
});
}else{
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkbox1"
});
}
});
});
// JSON.stringify(toDelete);
$('input:checkbox').change(
function(){
if ($(this).is(':checked')) {
toDelete.push(this.name);
}
return true;
}
);
$(document).ready(function(){
$("#btn").click( function() {
$.post( $("#myForm").attr("action"),
$('#str').val(JSON.stringify(toDelete))
);
});
$("#myForm").submit( function() {
return false;
});
});
</script>
</body>
</html>
As you are printing a string, not a javascript variable, you don't have quotes within alert call.
Change the line:
echo"<script> alert(".$x.");</script>";
With:
echo "<script> alert('$x'); </script>";
Or:
echo "<script> alert('".$x."'); </script>";
here is my html:
<form action="submitPage.php" method="post" onsubmit="savePathInVar();">
<table>
<tr>
<td><img id="' . $id . '" src="inventory_images/' . $id . '.jpg" onclick="changecolor();" /></td>
<td><img id="' . $id . '" src="inventory_images/' . $id . '.jpg" onclick="changecolor();" /></td>
</tr>
<input type="hidden" value="ClickedImaged" />
<input type="submit" value="Submit" />
</table>
</form>
Now i need a function changeColor() to highlight the one clicked image..
and the function savePathInVar() to save the clicked image´s path in the input-hidden-field.
Anyone who can help me?
ps: this is where $id comes from:
$sql = mysqli_query($mysqli, "SELECT * FROM products WHERE id='$id' LIMIT 1");
$productCount = mysqli_num_rows($sql); // count the output amount
if ($productCount > 0) {
// get all the product details
while($row = mysqli_fetch_array($sql)) {
$id = $row["id"];
$id = "img.$id";
blabla...
would be really nice if anyone could help me.. i am quite new to javascript :)
This was added to the answer by OP. It belongs to the question
EDIT:
Am I doing someone's homework
UPDATE 3, my whole code:
<script>
function changecolor(img)
{
var images = document.getElementsByTagName("img");
for(var i=0,j=images.length; i<j; i++)
{
images[i].style.borderColor="#000";
}
img.style.borderColor="#F00";
//Operate on img location as before
savePathInVar(img.src);
}
function savePathInVar(ImgLocation)
{
var form = document.createElement("form");
var inp = document.createElement("input");
inp.name="imgSrc";
inp.value=ImgLocation;
form.appendChild(inp);
form.method="post";
form.submit();//this will refresh the page
}
</script>
<form name="form_name" action="submitPage.php" method="POST" onsubmit="savePathInVar();">
<table>
<tr>
<td><img src="<?php echo $path; ?>" onclick="changecolor(this);" /></td>
<td><img src="<?php echo $path; ?>" onclick="changecolor(this);" /></td>
</tr>
<input type="submit" value="Submit" />
</table>
</form>
And my submitPage.php :
<?php
error_reporting (E_ALL | E_STRICT);
ini_set ('display_errors' , 1);
$imgSrc = $_POST['imgSrc'];
echo $imgSrc;
?>
when i mark an image and click "submit", i get:
Notice: Undefined index: imgSrc in /srv/disk8/1391019/www/myfirststore.eu.pn/submitPage.php on line 5
what do i have to do ?? greetings and thanks for your help.
Change onclick="changecolor();" to onclick="changecolor(this);"
function changecolor(img)
{
savePathInVar(img.src);
}
function savePathInVar(ImgLocation)
{
//Do what you want with ImgLocation
}
UPDATE
To unhighlight all images but one img:
function changecolor(img)
{
var images = document.getElementsByTagName("img");
for(var i=0,j=images.length; i<j; i++)
{
images[i].style.borderColor="#000";
}
img.style.borderColor="#F00";
//Operate on img location as before
savePathInVar(img.src);
}
UPDATE 2
To submit the image src to php, create a form and post it:
function savePathInVar(ImgLocation)
{
var form = document.createElement("form");
var inp = document.createElement("input");
inp.name="imgSrc";
inp.value=ImgLocation;
form.appendChild(inp);
form.method="post";
form.submit();//this will refresh the page
}
In php:
$imgSrc = $_POST['imgSrc'];
I have fixed the problem of the table working within a form. I just added an extra <td> field and created a hidden input field within it that will POST a separate tipID for each tip in the table. The entire table is also wrapped with the form tag to get the tipID to POST to the next page.
Now I need to know how make each individual table row send the data from the form kind of like each one being a button or making a hidden button click onclick of one of these table rows.
<form method="post" action="tips.php">
<div id="tippanel">
<table id="tippabl">
<tbody>
<?php if(!empty($tips))
while ($recd = mysql_fetch_array($tips, MYSQL_ASSOC)) {
echo "<tr> <td class='tiptxt' >"; echo $recd['tip_desc']; echo "</td> <td class='tiptime'>";
echo "<span>".date('H:i', strtotime($recd['datetime']))."</span>"; echo "</br>";
echo date('m-d-y', strtotime($recd['datetime'])); echo"</td><td><input type=";
echo '"hidden" '; echo 'name='; echo '"tip_id" '; echo 'value="';
echo ($recd['tip_id']); echo'"></td></tr>';
}
?>
</tbody>
</table>
</div>
</form>
My next page will use the query below and echo the full tip_desc since a tip can be several hundred characters. It will also have a text area in which an admin can send a message back to the original user.
My PHP and query should look like this on the next page:
<?php
$tipID = $_POST['tipID'];
mysql_query="SELECT * FROM tips WHERE tipID = $tipID";
?>
Just surround your table into a form, place a hidden input field into it.
<form action="tips.php">
<input name="tipID" type="hidden" value="id" />
<div id="tippanel">
<table id="tippabl">
<tbody>
<?php
if(!empty($tips)) {
while ($recd = mysql_fetch_array($tips, MYSQL_ASSOC)) {
echo "<tr> <td class='tiptxt' >"; echo $recd['tipDescription'];
echo "</td> <td class='tiptime'>";
echo "<span>".date('H:i', strtotime($recd['dateTime']))."</span>";
echo "</br>"; echo date('m-d-y', strtotime($recd['dateTime']));
echo"</td></tr>";
}
}
?>
</tbody>
</table>
</div>
</form>
Have a look at this to make your rows clickable. Working demo
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
Credit: SolutionYogi
Ref: Adding an onclick event to a table row