Why are my checkbox and double-click functions not responsive? [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I have this code making a table on the fly with a checkbox, and refreshing after a minute. The checkbox and double-click functions are not working, and I'm not sure why. Please help.
<script type='text/javascript'>
function vehicle() {
$('#Vehicles').html(
<?php
$username =$_SESSION['user_name'];
$sql = "select * from gps_product where gp_userid ='$username'";
$db = new DbClass($sql);
echo '"<table>';
echo '<tr>';
echo '<th>Name</th>';
echo '<th>Driver</th>';
echo '<th>Last Seen</th>';
echo '<th>Follow</th>';
echo '<th>Status</th>';
echo '<th>Speed</th>';
echo '<th>Engine</th>';
echo '<th>Address</th>';
echo '</tr>';
while ($db->fetch_array()){
$timezone = $db->get('gp_timezone');
$sql2 = "SELECT *, date_add(gm_gpstime, INTERVAL ".$timezone." HOUR) gpstime FROM gps_msg
WHERE gm_imei = '" . $db->get('gp_imei') . "' AND gm_event = '0' ORDER BY gm_gpstime desc LIMIT 1;";
$db2 = new DbClass($sql2);
while ($db2->fetch_array()) {
echo '<tr id=\''.$db->get("gp_imei").'\' class=\'Vehicle\'>';
echo '<td>';
echo $db->get("gp_name");
echo '</td>';
echo '<td>';
if ($db->get("gp_sopir"))
echo $db->get("gp_sopir");
echo '</td>';
echo '<td>';
echo ago(time() - timeToSecond($db2->get('gpstime'), 0));// berapa detik yang lalu
echo '</td>';
echo '<td>';
echo '<center><input type=\'checkbox\' class=\'checkbox\' id=\'';
echo $db->get("gp_imei");
echo '\'></input></center>';
echo '</td>';
echo '<td>';
$mode = cekStatusGPS($db2->get('gm_accuracy'), substr($db2->get('gm_devicestate'),0,2));
echo '<center><img src=\'status/'.$mode.'.png\' width=\'20px\' height=\'20px\'></center>';// status
echo '</td>';
echo '<td>';
echo $db2->get('gm_speed').'km/h';// Kecepatan
echo '</td>';
echo '<td><center>';
if (substr($db2->get('gm_devicestate'),0,1) == '1'){
$engine = 'off';
}
else if(substr($db2->get('gm_devicestate'),0,1) == '2'){
$engine = 'on';
}
echo $engine;// engine on/off
echo '</center></td>';
echo '<td>';
if ($db->get('gp_rgeo') == 1) {
$posisi = parse_location($db2->get('jalan'). "," . $db2->get('kota'). "," . $db2->get('kabupaten'). "," . $db2->get('propinsi'). "," . $db2->get('negara'). "," . $db2->get('landmark'));
}
else{
$posisi = result_location($db2->get('gm_lat'),$db2->get('gm_lng'));
}
echo $posisi;// alamat
echo '</td>';
echo '</tr>';
}
}
echo '</table>"';
?>
);
}
$(document).ready(function() {
$('#Map').html('<object data="map.php?user=<?php echo $_SESSION['
user_name ']?>" width="100%" height="100%">');
$(function() {
vehicle();
setInterval(vehicle, 60000);
});
$('.checkbox').change(function() {
if (this.checked) {
$('#Map').html('<object data="map.php?imei=' + this.id + '" width="100%" height="100%">');
$('.checkbox').not(this).prop('checked', false);
} else {
$('#Map').html('<object data="status.php?user=<?php echo $_SESSION['
user_name ']?>" width="100%" height="100%">');
}
});
$('.Vehicle').dblclick(function() {
$('#Status').html('<object data="status.php?imei=' + this.id + '" width="100%" height="100%">');
});
});
</script>
i just want to refresh that vehicle div but when i use coding like that checkbox and double-click functions are not working.

Since you added elements to your page via the echo of PhP, you have to bind them again with .on()
So instead of $('.checkbox').change(function(){});,
change it to $('#Vehicles').change('change', '.checkbox', function(){});
and add that change to your echo.
Note that this will make your PhP messy, so I suggest making the binding into a js function, then calling that function on your echo

Related

How can I access the values of a checkbox outside of the form action that it is declared in?

I successfully created a script that will delete the rows of a table if a checkbox is checked on that row (the checkbox holds the rowID). The checkboxes and button to delete these rows are inside of the same form tags. Now I want to create another button that uses the value of the checkboxes to do a different update statement, but the values of the checkboxes are not appearing in $_POST on this separate page.
Does anyone know how to make the checkbox values accessible outside of the form action it is inside of? Here is my reduced code for the delete that works:
The function below is called on PickTicket.php to display a table.
Function DisplayPickTicket() {
$conn = getDBConnection();
$sql = "SELECT * FROM dbo.BK_NotesRecord WHERE StatusID = 1 ";
$stmt = sqlsrv_query( $conn, $sql );
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true) );
}
echo '<form action="updatepickstatus.php" method="post">';
// Delete Checkbox header.
echo '<th class="table-header" style="width:5px;">';
echo 'Delete';
echo '</th>';
// Inventory number header.
echo '<th class="table-header" style="width:90px;">';
echo 'Inventory #';
echo '</th>';
//InventoryID Header
echo '<th class="table-header" style="width:40px;">';
echo 'InventoryID';
echo '</th>';
if (sqlsrv_has_rows($stmt)) {
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
echo '<tr>';
//Delete checkbox
echo '<td class="cell"><div class="cell">';
echo '<input type = "checkbox" name="chkbox[]" value= "' .$row['InventoryID'].
'">';
echo '</td>';
// Inventory#
echo '<td class="cell"><div class="cell">';
echo $row["InventoryNumber"];
echo '</td>';
// InventoryID.
echo '<td class="cell"><div class="cell">';
echo $row["InventoryID"];
echo '</td>';
}
}
echo "<tr>";
echo "<td>";
echo "<input type='submit' name='submit' Value='Remove'>";
echo '</form>';
echo "</td>";
echo "</tr>";
This is updatepickstatus.php:
<?php
$serverName = "(local)";
$connectionOptions = array("Database"=>"Powerlink");
$conn = sqlsrv_connect( $serverName, $connectionOptions);
if( $conn === false ) {
echo "Connection failed!<br>";
die( print_r( sqlsrv_errors(), true));
}
if (isset($_POST['chkbox'])) {
foreach($_POST['chkbox'] as $Update) {
$sql = "UPDATE BK_NotesRecord set StatusID = '2' WHERE InventoryID LIKE '".$Update."'";
$stmt = sqlsrv_query( $conn, $sql );
//echo '$ids';
}
}
print_r($_POST);
?>
^^I want to accomplish this same basic task, but outside of updatepickstatus.php. When applying similar logic to check the values of the selected checkboxes on a different I get an empty array. Any thoughts?
Try declaring a variable and passing the value you want to use to it then use sessions to move it where ever you want.

How do I hide the load more button for this jquery code

I am trying to make a website but I am very new to the jquery stuff and I added jquery load more comment into my website
My question is, I have a load more button that works the way I intended it to work however when all the data are loaded or when there is no comment I can't seem to get the load button to turn hidden
//jquery script
<script>
$(document).ready(function() {
var commentCount = 20;
var qidNow = "<?php echo $qid; ?>";
$("button").click(function() {
commentCount = commentCount + 20;
$("#comments").load("includes/load-comments.inc.php", {
commentNewCount: commentCount,
qid: qidNow
});
});
});
//load-comments page
<?PHP
require 'dbh.inc.php';
include 'function.inc.php';
$commentNewCount = $_POST["commentNewCount"];
$qid = $_POST["qid"];
$count = 0;
$sqlComment = "SELECT comment, commentTime, commenterId FROM comments WHERE commentOn = ?
LIMIT ?";
$stmtComment = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmtComment, $sqlComment)) {
header("Location: ../viewtopic.php?error=sqlerror4");
exit();
} else {
//bind parameter to the placeholder
mysqli_stmt_bind_param($stmtComment, "ii", $qid, $commentNewCount);
//run parameter inside database
mysqli_stmt_execute($stmtComment);
$commentData = mysqli_stmt_get_result($stmtComment);
}
if (mysqli_num_rows($commentData) > 0) {
while ($row = mysqli_fetch_assoc($commentData)) {
$count++;
echo "<div class='individualComment'>";
echo "<div class='commentCount'> คอมเม้นที่" . $count . "</div>";
echo "<div class='actualComment'>" . $row['comment'] . "</div>";
echo "<div class='commentDateBx'>" . dateReformat($row['commentTime']) . "</div>";
echo "<div class='commenterIdBx'>ID :" . $row['commenterId'] . "</div>";
echo "</div>";
}
}else {
echo "There is no comment yet";
}

PHP while loop first button is not working

I have created a while loop for the data fetched from the database. I have added a button to each loop. when the user clicks on the button, it should open a new tab and since I am using the form method="GET" the data is getting passed to the new tab window.
This is not working only for the first loop button, whereas it is working fine for all other buttons created by the loop. Can someone help? The code is as below:
$result = mysqli_query($link, $query);
if ($result->num_rows > 0) {
// output data of each row
$row = 1;
$number = 1;
while($row = $result->fetch_assoc()) {
echo '<tr>';
$invoiceNumber = $row["invoiceNumber"]`enter code here`;
echo ' <td align="center" style="text-align:center">' . $invoiceNumber . '</td>';
echo ' <td align="right">' . $row["invoiceDate"] . '</td>';
echo ' <td align="right">' . $row["accountName"] . '</td>';
$beginTime = $row["beginTime"];
$beginTime = date("D, j M Y", strtotime($beginTime));
echo ' <td align="right">' . $beginTime . '</td>';
$endTime = $row["endTime"];
$endTime = date("D, j M Y", strtotime($endTime));
echo ' <td align="right">' . $endTime . '</td>';
echo ' <td align="center"style="text-align:center"><form method = "GET" action= "invoice.php" name="'.$number.'"><button name= "invoice" value='.$invoiceNumber.'></form>View</button></td>';
echo '</tr>';
$number = $number + 1;
}
} else {
echo "0 results";
}
Saw that the form closing tag </form> is inside the <button> tag, would you try to change it to:
<td align="center"style="text-align:center">
<form method = "GET" action= "invoice.php" name="'.$number.'">
<button name= "invoice" value='.$invoiceNumber.'>View</button>
</form>
</td>
See if it helps..
I edited the code and removed the form tag. It works perfectly for all buttons now including the first button in while loop. Code is as below :
echo ' <td align="center"style="text-align:center"><button id="invoice" name= "invoice[]" value='.$invoiceNumber.'>View</button></td>';
<?php
if ($_POST['invoice']) {
$name = $_POST['invoice'];
$array = $name[0];
//echo $array;
echo '<script>window.open("invoice.php?'.$array.'","_blank")</script>';
}
?>

value of $_POST is always the last value of my <tr>

I have a problem in which I cannot solve. I have a simple page where I query all Users and list them in a table. When a user clicks on one of the table rows, it should be taken to another page where the user can edit information of the that they picked. The problem is that in my script, the $_POST value is always the value of the last
CODE
<?php
include "conn.php";
$pquery = "SELECT * FROM Patient NATURAL JOIN User ORDER BY LastName;";
$patientQuery = $conn->query($pquery);
if (mysqli_num_rows($patientQuery) == 0)
echo "<p>No patients found.</p>";
else{
while($assoc = $patientQuery->fetch_assoc()){
echo "<tr onclick = 'sub();'>";
echo "<td>";
echo $assoc['UserID'];
echo "<input type = 'hidden' name = 'UserID' value = '". $assoc['UserID'] ."' />";
echo "</td>";
echo "<td>";
echo $assoc['FirstName'];
echo "</td>";
echo "<td>";
echo $assoc['LastName'];
echo "</td>";
echo "</tr>";
}
}
?>
<script>
function sub(){
document.getElementById("edit").submit();
return false;
}
</script>
I've slightly modified your code - this should work:
<?php
include "conn.php";
$pquery = "SELECT * FROM Patient NATURAL JOIN User ORDER BY LastName;";
$patientQuery = $conn->query($pquery);
if (mysqli_num_rows($patientQuery) == 0)
echo "<p>No patients found.</p>";
else{
while($assoc = $patientQuery->fetch_assoc()){
echo "<tr onclick = 'sub(". $assoc['UserID'] .");'>";
echo "<td>";
echo $assoc['UserID'];
echo "</td>";
echo "<td>";
echo $assoc['FirstName'];
echo "</td>";
echo "<td>";
echo $assoc['LastName'];
echo "</td>";
echo "</tr>";
}
}
?>
<script>
function sub(UserID){
document.location.href = 'http://www.yourdomain.com/something.php?UserID='+UserID;
return false;
}
</script>

Form in a PHP inside auto-refresh DIV tag won't work

I have the following two pages. The index.php includes purchases_pending.php through PHP. The first time the page loads the form works perfectly but when the DIV(#pp) is refreshed after 10 seconds the FORM does not work. Is there a solution for this? Or if I can do it through AJAX, can somebody help me with the code. As you have seen my codes you'll probably know Im a beginner.
Thanks in advance.
index.php
<script type="text/javascript">
function update(){
$('#pp').load('/status/purchases_pending.php');
}
setInterval( update, 10000 );
</script>
<div class="content">
<div class="content_left">
<p>
<h3>Pending Purchases</h3>
<div class="user_content"><div id="pp"><?php include ($purchases_pending); ?></div></div>
</p>
purchases_pending.php
<?php
$CONFIG = $_SERVER["DOCUMENT_ROOT"]. "/config/";
include($CONFIG. "pages.php");
include($db);
$sql = "SELECT * FROM account WHERE status='Pending' AND type='Purchase'";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
echo '<table>';
echo '<tr> <th align="left">Party</th> <th>Box</th> <th>Rate</th> <th>Status</th> </tr>';
while ($result = mysqli_fetch_assoc($query)) {
$id = $result['id'];
$party = $result['party'];
$box = $result['box'];
$rate = $result['rate'];
$amount = $result['amount'];
echo '<form action="" method="post">';
echo '<tr>';
echo '<td>' . $party . '</td>';
echo '<td align="center">' . $box . '</td>';
echo '<td align="right">' . $rate . '</td>';
echo '<td align="center"><input type="checkbox" name="status[]" id="status[]" value="' . $id . '" /></td>';
echo '</tr>';
}
echo '</table>';
echo '<input type="submit" name="submit" value="Completed" class="input" />';
echo '</form>';
}
else {
echo 'Hooray...No pending purchases';
}
if(isset($_POST['submit']) && $_POST['submit']!="") {
$status = $_POST['status'];
$count = count($_POST['status']);
for($i=0;$i<$count;$i++) {
$update_purchases = "UPDATE account SET status='Completed', user_confirm='$user_confirm' ,user_confirm_time=current_timestamp WHERE id='$status[$i]'";
$query_purchases = mysqli_query($conn, $update_purchases);
}
header ('location:/');
}
?>
load the JS function outside the jquery
<script>
function update(){
$('#pp').load('/status/purchases_pending.php');
}
</script>
$( document ).ready(function() {
setInterval( update, 10000 );
});
JS load needs to be in document ready in order to work.
Short hand is
$(function() {
var update = function() {
$('#pp').load('/status/purchases_pending.php');
setTimeout(update, 10000);
}
update();
});
Move this code to index.php as this no longer exist in the page because it gets removed when replacing div #pp
if(isset($_POST['submit']) && $_POST['submit']!="") {
$status = $_POST['status'];
$count = count($_POST['status']);
for($i=0;$i<$count;$i++) {
$update_purchases = "UPDATE account SET status='Completed', user_confirm='$user_confirm' ,user_confirm_time=current_timestamp WHERE id='$status[$i]'";
$query_purchases = mysqli_query($conn, $update_purchases);
}
To explain php renders from the server as html, it reads top to bottom.
So when the js inserts it, it is not inserting the code, but rather the rendering of the code.
Ajax is used to send data, but on load no data is being sent other than give me a form.
The post doesn't exist because it is already rendered. When using an include it is "inserted" as part of the code to be executed and thus works.

Categories

Resources