PHP while loop first button is not working - javascript

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>';
}
?>

Related

Updating mySQL table with user interface - PHP

[Sample Look]
I'm trying to make an interface where you can edit/add/remove fields of a mySQL database. This is how it looks visually, and I have all the functionality on the client side working.
My question is: How can I pass any edits/adds/removals to the server side? I'll include a link for my JSFiddle.
And the code below will show how I currently great the table.
<?php
$servername = "localhost";
$username = "lalalal";
$password = "lalalal";
$link = mysqli_connect("localhost", "lalala", "lalala", "lalala");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sqlStart = "SELECT `Name`, `EXT`, `Returning Time`, `Returning Date`, `Out`, `Reset`, `Booked` FROM `lalala`";
if($result = mysqli_query($link, $sqlStart)){
if(mysqli_num_rows($result) > 0){
echo "<table id = contactTable>";
echo "<tr id = row1>";
echo "<th id = sortTable onclick=sortTable(0)>Name ↕</th>";
echo "<th style = width:100px;>EXT</th>";
echo "<th style = width:300px;>Returning Time</th>";
echo "<th style = width:300px;>Returning Date</th>";
echo "<th style = width:70px;>Out</th>";
echo "<th style = width:100px;>Reset</th>";
echo "<th style = width:600px;>Booked</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
$currentCheck = $row['Out'];
if ($currentCheck == 0) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
if ($currentTime == 0) {
echo "<td> <form> <input type = 'time', id = 'timePickChange'> </form> </td>";
} else {
echo "<td> <form> <input type = 'time', id = 'timePickChange' value =" . $currentTime . "> </form> </td>";
}
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = 'datePickChange' value =" . $currentDate . "> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)'> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
} else if ($currentCheck == 1) {
echo "<tr style = 'background-color: #E2E9FD'>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
echo "<td> <form> <input type = 'time', id = timePickChange disabled> </form> </td>";
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = datePickChange disabled> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)' checked> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
}
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sqlStart. " . mysqli_error($link);
}
?>
Depending on your data validation model, you might want to control the inputs value client side before posting them to your back-end.
AFAIK, you're already adding/editing/removing your contacts on the client side, so If I understand correctly, when your user should click on Edit/Remove & confirm , it would be a confirmation of what the user has done in the browser, this doesn't really change much apart from the fact that otherwise you might need dedicated buttons/row (or any other bindable events).
For these operations what you could do is proceed to bulk delete / edit, and this could be easily done by filtering out in your JS all the modified/deleted data and sending it to your back end PHP with Ajax/jQuery in the form of a stringified array.
As for insertion operation you'd submit them at the same time you add them to your table, by executing a POST operation.
And it could be done with something like this :
$.ajax({
method: "PUT",
url: "some.php",
data: JSON.stringify(myUpdatedDataInAnArray)
// you might need to stringify your array to ensure format ?
})
.done(function( msg ) {
alert( "Data Updated: " + msg );
});
In your back end php, you'd listen for POST/PUT/DELETE methods with something like that :
if (isset($_POST['add'])){
do your thing
}
if (isset($_PUT['updated'])){
//Since you're sending a stringified array, you must parse it with
$myArray = json_decode($_PUT['updated']);
do your thing
}
if (isset($_DELETE['deleted'])){
do your thing
}
I say Ajax because using a traditional POST/PUT/DELETE form would result in refreshing the page.
Here are some useful refs :
JS JSON Stringify and JSON Parse
PHP : JSON DECODE and JSON Encode
Ajax docs
Ajax Examples

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

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

ajax not firing on change to contenteditable cell

I have a contenteditable table which when edited should update a table in the database via ajax but nothing is happening to the database when I change the values.
<div id="activities2" class="activities2"> <?
$q2a="SELECT activityid, activitynumber, title, description, leaders, time FROM activities where activities.meetingid='$id' AND activities.unitid='$input2'";
$r2a=mysqli_query($dbc,$q2a) or die(mysqli_error($dbc));
echo "<table class='layouttable'><tr><td>ActivityNumber</td><td>Title</td><td>Description</td><td>Leaders</td><td>Time</td><td>Edit</td>";
while($row2a
=mysqli_fetch_assoc($r2a))
{
echo "
<tr>
<td contenteditable='true' id='activitynumber:" . $row2a['activityid'] . "'>" . $row2a['activitynumber'] . "</td>
<td contenteditable='true' id='title:" . $row2a['activityid'] . "'>" . $row2a['title'] . " </td>
<td contenteditable='true' id='description:" . $row2a['activityid'] . "'>" . $row2a['description'] . " </td>
<td contenteditable='true' id='leaders:" . $row2a['activityid'] . "'>" . $row2a['leaders'] . " </td>
<td contenteditable='true' id='time:" . $row2a['activityid'] . "'>" . $row2a['time'] . " </td>
</tr>.
";
}
echo"</table>"; ?><br><Br></div>
The javascript for ajax is:
<script name = 'inlineedit'>
$(document).ready(function(){
$("td[contenteditable=true]").blur(function(){
var msg = $(".alert");
var newvalue = $(this).text();
var field = $(this).attr("id");
$.post("activityupdate.php",field+"="+newvalue,function(d){
var data = JSON.parse(d);
msg.removeClass("hide");
if(data.status == '200'){
msg.addClass("alert-success").removeClass("alert-danger");
}else{
msg.addClass("alert-danger").removeClass("alert-success");
}
msg.text(data.response);
setTimeout(function(){msg.addClass("hide");},3000);//It will add hide class after 3 seconds
});
});
});
</script>
and the php file doing the editing (though it doesnt seem to be getting this far is:
<?
$response = NULL;
$status = http_response_code(406);
if(!empty($_POST)){
include "connect_db.php"; //Including Database Settings
foreach($_POST as $key=>$value){
$key = strip_tags(trim($key));
$value = strip_tags(trim($value));
$explode = explode(":",$key);
$activity_id = $explode[1];
$field_name = $explode[0];
if(isset($activity_id)){
$query = "UPDATE activities SET $field_name='{$value}' WHERE activityid='$activity_id'";
$update = mysqli_query($dbc,$query) or die(mysqli_error($dbc)); //Update the activity Table
if($update){
$response = "User Details Updated";
http_response_code(200); //Setting HTTP Code to 200 i.e OK
}else{
$response = "Not Modified";
http_response_code(304); //Setting HTTP Code to 304 i.e Not Modified
}
}else{
$response = "Not Acceptable";
}
}
}
echo json_encode(array(
"status"=>$status,
"response"=>$response
));
?>
You would need few changes in code:
Instead of setting contenteditable='true' use class='editable'.
in the js try using on change instead of blur.
$("td.editable").on ("change",function(){....
this would execute ajax on every change in the editable fields.

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.

Clickable data displayed from mysql using PHP

I'm not very good at JavaScript but here is my problem.
I have three pages: page1.php, page2.php, page3.php
On page1.php, I have a form for users to select grade level they want to view, then the action is performed on page2.php -- displaying the list of all students in that grade.
This is the code for page2.php
<?php
//database variables
require_once('admin_settings.php');
//these variables are from a form used to display the current data
$level = $_POST['level_group'];
$room = $_POST['room_group'];
$con=mysqli_connect("$host","$dbuser","$dbpass","$dbname");
mysqli_set_charset($con, "utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT std_id, std_name FROM students WHERE std_level LIKE '$level%' AND std_room LIKE '$room';");
//table
echo"
<table border='1' id='mytable'>
<tr bgcolor = #99CCFF>
<th><b>Student ID</b></th>
<th><b>Name</b></th>
<th><b>Action</b></th>
</tr>";
//loop through the database
while($row = mysqli_fetch_array($result))
{
echo"<form action='view_one_student.php' method='post'>";
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo "<td>" . '<input type="submit" value="view"> <input type="submit" value="sdq">' . "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
?>
The question...now is How can I write the code on page3.php so that when users clicks on view or sdq button next to each column, the student ID should be captured, send a request to the database, and query other data related to this particular student such as age, address, phone..etc. and display them on that page3.php
page2.php
You have to add a hidden input with the id of the student in page2.
<input type="hidden" value="'.$row["std_id"].'" name="std_id">
Change your action page to page3 (if that's where you want to display the student info: name, age...)
<form action='page3.php' method='post'>page2.php
The code for page2:
<?php
//database variables
require_once('admin_settings.php');
//these variables are from a form used to display the current data
$level = $_POST['level_group'];
$room = $_POST['room_group'];
$con=mysqli_connect("$host","$dbuser","$dbpass","$dbname");
mysqli_set_charset($con, "utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT std_id, std_name FROM students WHERE std_level LIKE '$level%' AND std_room LIKE '$room';");
//table
echo"
<table border='1' id='mytable'>
<tr bgcolor = #99CCFF>
<th><b>Student ID</b></th>
<th><b>Name</b></th>
<th><b>Action</b></th>
</tr>";
//loop through the database
while($row = mysqli_fetch_array($result))
{
echo"<form action='page3.php' method='post'>";
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo "<td> <input type='hidden' value='" . $row["std_id"] . "' name='std_id'>";
echo "<input type='submit' value='view'>";
echo "<input type='submit' value='sdq'></td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
?>
page3.php
A posible solution for page3 can be: (add your columns you need: age, address, phone..)
<?php
//database variables
require_once('admin_settings.php');
//these variables are from a form used to display the current data
$id = $_POST['std_id'];
$con=mysqli_connect("$host","$dbuser","$dbpass","$dbname");
mysqli_set_charset($con, "utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM students WHERE std_id ='$id';");
echo '<h3>Student detail</h3>';
//table
echo"
<table border='1' id='mytable'>
<tr bgcolor = #99CCFF>
<th><b>Student ID</b></th>
<th><b>Name</b></th>
<th><b>Age</b></th>
</tr>";
//loop through the database
while($row = mysqli_fetch_array($result))
{
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo "<td>" . $row['std_age'] . "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
?>
You can modify your code like this. A hidden field will send the student id to the page of view_one_student.php.
while($row = mysqli_fetch_array($result))
{
echo"<form action='view_one_student.php' method='post'>";
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo '<input type="hidden" value="'.$row["std_id"].'" name="std_id">';
echo "<td>" . '<input type="submit" value="view"> <input type="submit" value="sdq">' . "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
On view_one_student.php you have to catch that with:
$_POST["std_id"]
And eventually input that into a sql sentense in view_one_student.php:
$sql = "SELECT * FROM <table> WHERE id=".$_POST["std_id"];
Thats the general idea.

Categories

Resources