Submitting looped values to database, one by one using ajax - php

Am developing results management system where a lecturer can login and update students' results.
The system exacts all students offering that course unit and the lecturer updates the marks.
I discovered that it is very monotonous for a lecturer to click a button to submit results for each student yet they are very many students and very many buttons appearing on every student extracted, Then i thought of using AJAX to submit results on "ONCHANGE call event".
The simple AJAX script is working well only that , it is picking the last student in the loop and stores results in line with his id even if you try storing results for other students. It will just update results for the last students.
Here is my code for the looped students.
Marks.php
<?php
$row=mysql_fetch_assoc($sql);//course unit information
if(mysql_num_rows(mysql_query("SELECT * FROM allocations WHERE courseunitid='".$row['courseunitid']."' AND acid='".$_POST['acid']."' AND semester='".$_POST['semester']."' AND adminid='".$_SESSION['adminid']."'"))<1){
echo "<b><i><font color=red>Sorry! This course unit was not allocated to you in the specified search</font></i></b>";
}else{
echo"<hr size=1>";
echo "<table>
<tr>
<td colspan=4><b>UPDATE RESULTS OF BELOW STUDENTS</b></td>
</tr>
<tr>
<td><b>NO</b></td>
<td><b>REG NO</b></td>
<td><b>NAME</b></td>
<td><b>TEST</b></td>
<td><b>EXAMS</b></td>
</tr>
";
$x=1;
$sql_results=mysql_query("SELECT students.*,results.* FROM results INNER JOIN students ON results.stid=students.stid WHERE results.courseunitid='".$row['courseunitid']."' AND results.acid='".$_POST['acid']."' AND results.regsem='".$_POST['semester']."' AND results.adminid='".$_SESSION['adminid']."'");
while($rows=mysql_fetch_assoc($sql_results)){
?>
<tr><td><?php echo $x++?> . </td><td> <?php echo strtoupper($rows['regno']) ?></td><td><?php echo ucwords($rows['fname']).' '.ucwords($rows['mname']).' '.ucwords($rows['lname']) ?></td><td><input type='text' name='test' value='<?php echo $rows['test'] ?>' style='width:40px;height:26px' maxlength='2' onblur='enter_results("test",this.value)'></td><td><input type='text' maxlength='3' name='exams' value='<?php echo $rows['exams']?> ' style='width:40px;height:26px' onblur='enter_results("exams",this.value)'></td><td id='<?php echo $rows['stid']?>'><?php echo $rows['stid'] ?></td></tr>
<script>
//Ajax Script for picking values (Marks)
function enter_results(marksname,marksvalue){
if(marksname=='test'){
document.getElementById('<?php echo $rows['stid'] ?>').innerHTML="<font color=green><i>Saving test marks...</i></font>";
}else{
document.getElementById('<?php echo $rows['stid'] ?>').innerHTML="<font color=green><i>Saving exam marks...</i></font>";
}
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(xhttp.readyState==4 && xhttp.status==200){
if(marksname=='test' || marksname=='exams' ){
document.getElementById('<?php echo $rows['stid'] ?>').innerHTML=xhttp.responseText;
}
}
}
xhttp.open('GET','../ajax_calls/ajax_call.php?marksname='+marksname+'&marksvalue='+marksvalue+'&rid=<?php echo $rows['rid']?>',true);
xhttp.send();
}
</script>
<?php
}
echo "</table>";
?>

1st : Your creating multiple javascript function inside the while loop it was wrong approach . you need to create single function and call with dynamic parameter .
onblur='enter_results("test",this.value,"<?php echo $rows[\'stid\'] ?>","<?php echo $rows[\'rid\'] ?>")'>
Note: Added student id and row id as third and fourth parameter in function call .
PHP :
<hr size=1>
<table>
<tr>
<td colspan=4><b>UPDATE RESULTS OF BELOW STUDENTS</b></td>
</tr>
<tr>
<td><b>NO</b></td>
<td><b>REG NO</b></td>
<td><b>NAME</b></td>
<td><b>TEST</b></td>
<td><b>EXAMS</b></td>
</tr>
<?php
$x=1;
?>
//while loop start here
<tr>
<td><?php echo $x++?> . </td>
<td> <?php echo strtoupper($rows['regno']) ?></td>
<td><?php echo ucwords($rows['fname']).' '.ucwords($rows['mname']).' '.ucwords($rows['lname']) ?></td>
<td><input type='text' name='test' value='<?php echo $rows['test'] ?>' style='width:40px;height:26px' maxlength='2' onblur='enter_results("test",this.value,"<?php echo $rows[\'stid\'] ?>","<?php echo $rows[\'rid\'] ?>")'></td>
<td><input type='text' maxlength='3' name='exams' value='<?php echo $rows['exams']?> ' style='width:40px;height:26px' onblur='enter_results("exams",this.value)'></td>
<td id='<?php echo $rows['stid']?>'><?php echo $rows['stid'] ?></td>
</tr>
//while loop end here
</table>
Javascript : Script should be outside the while loop .
<script>
//Ajax Script for picking values (Marks)
function enter_results(marksname,marksvalue,stdid,rowid){
if(marksname=='test'){
document.getElementById(stdid).innerHTML="<font color=green><i>Saving test marks...</i></font>";
}else{
document.getElementById(stdid).innerHTML="<font color=green><i>Saving exam marks...</i></font>";
}
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(xhttp.readyState==4 && xhttp.status==200){
if(marksname=='test' || marksname=='exams' ){
document.getElementById(stdid).innerHTML=xhttp.responseText;
}
}
}
xhttp.open('GET','../ajax_calls/ajax_call.php?marksname='+marksname+'&marksvalue='+marksvalue+'&rid='+rowid,true);
xhttp.send();
}
</script>

Related

How to echo a table in two piece separated code in PHP?

Now I wish to construct a list of tables under nested while loop and if-else condition with PHP, the format of the code is as below:
while(){
if (){
..... // extract the data
while(){
construct a table using the data extracted above
}
}
elseif (){
..... // extract the data
while(){
construct a table using the data extracted above
}
}
}
Specifically, in the inner while loop the code is:
while ( $chat = mysqli_fetch_assoc($chatQ))
{
echo
"<table class='table table-hover' >"
."<td>"
.$conver['sender_name']."\t".$chat['sender']."\t".$chat['send_time']."\t".$chat['content']
."</td>"
."<td>"
."<form id='join' action='group_chat.php' method ='POST' accept-charset='UTF-8'>"
// post the group id
."<input type='hidden' name='group_id' id='group_id' value=".$conver['sender_id']."/>"
."<button class='btn btn-default' type='submit'>Enter</button>"
."</form>"
."</td>"
."</table>";
}
But the result is very ugly:
The problem is that the Enter button is associated with each message. But what I want is that after displaying all the messages, there is a Enter button which can direct to the specific group. But I don't know how to separate the code. Could you please do me a favor? Thanks in advance!
You can do something like this:
<?php
$counter = 0;
echo '
<form>
<table>';
while ( $chat = mysqli_fetch_assoc($chatQ)){
$counter++;
echo '
<tr>
<td>
group_id_'.$counter.'
</td>
<td>
<input name="group_id_'.$counter.'" value="'.$conver['sender_id'].'">
</td>
</tr>';
}
echo '
<tr>
<td colspan="2">
<button type="submit">Enter</button>
</td>
</tr>
</table>
</form>';
?>
Also you dont have to limit yourself to echo everything in order by setting variables. See example below:
<?php
$counter = 0;
$data = NULL;
while ( $chat = mysqli_fetch_assoc($chatQ)){
$counter++;
$data .='
<tr>
<td>
group_id_'.$counter.'
</td>
<td>
<input name="group_id_'.$counter.'" value="'.$conver['sender_id'].'">
</td>
</tr>';
}
echo '
<form>
<table>'.$data.'
<tr>
<td colspan="2">
<button type="submit">Enter</button>
</td>
</tr>
</table>
</form>';
?>

PHP/MYSQL: A removed row is still displayed in my page after a reload

I work on a simple webserver on a Raspberry Pi, displaying a MySQL table with two buttons : One (Switch) to inverse a boolean value, and one (Delete) to remove the entire row from the table.
What I do, basically, is a while loop on the MySQL table in which I : 1 : display the row and the buttons in a form, and 2 : check if the buttons have been clicked, and if so I send the query to the database and reload the page.
My problem is very simple : When I click on a "switch" button, the query is sent and the page is refreshed, and the value is correctly modified (the page display the value as it is in the database). But when I click on the other button, the "delete" one, after the page has been reloaded, the row still appears in the table. Only when I manually reload the page, the row disappear.
What I already tried :
1 : Check that the row is removed from the database BEFORE the manual refresh : DONE, and the row is correctly removed.
2 : Wait 500ms after the MySQL query, and then reload the page : DONE, and even when I wait 500ms, when the page reloads there is still the removed row.
Here is the whole code, the MySQL query is at the end :
<form action="logout.php" method="post">
<input type="submit" name="logout" value="logout">
</form>
<b>Alarm Monitoring</b>
<p>Sensors state table. Clicking on "Switch state" will switch the field "state" of the associated mote. </p>
<p>State 1 means that the mote is active, the alarm will be activated if the mote is moved or if someone is detected.</p>
<p>State 0 means that the mote is inactive, the alarm will NOT be activated if the mote is moved or if someone is detected.</p>
<?php
$servername="localhost";
$username="root";
$password="patate";
$dbname="testbase";
$table="matable";
$conn = new mysqli($servername,$username,$password,$dbname);
if ($conn->connect_error) {
echo "kaput";
die("Connection failed: " . $conn->connect_error);
}
$sql="SELECT * FROM $table;";
$result=$conn->query($sql); ?>
<table border=0>
<tr>
<td>
<table border=1>
<tr>
<td width=150>ID</td>
<td width=150>Date</td>
<td width=300>PIR</td>
<td width=150>Accel</td>
<td width=100>State</td>
<td width=150>Switch</td>
<td width=150>Delete</td>
</tr>
<?php
while($row = $result->fetch_assoc()) : ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['pir']; ?></td>
<td><?php echo $row['accel']; ?></td>
<td><?php echo $row['state']; ?></td>
<form name="form1" method="post" action=''>
<td><?php echo "<input name='Switch' type='submit' id='Switch' value='Switch state ".$row['id']."'>"; ?></td>
<td><?php echo "<input name='Delete' type='submit' id='Delete' value='Delete mote ".$row['id']."'>"; ?></td>
</form>
</tr>
<?php
if($_REQUEST['Delete']=='Delete mote ' . $row['id']) {
{
$sql3="DELETE FROM $table WHERE id=".$row['id'].";";
$result3=$conn->query($sql3);
header('Location: table.php');
}
}
if($_REQUEST['Switch']=='Switch state ' . $row['id']) {
{
if($row['state']=='1')
{
$sql2="UPDATE $table SET state='0' WHERE id=".$row['id'].";";
}
else
{
$sql2="UPDATE $table SET state='1' WHERE id=".$row['id'].";";
}
$result2=$conn->query($sql2);
header('Location: table.php');
}
}
?>
<?php endwhile; ?>
</table>
</table>
</td>
</tr>
</table>
Maybe someone saw this problem before ?
whell you are have problem with redirect. check this link to know more about redirect
Before you continue please backup your code.
To fix your problem you must move your <?php endwhile; ?> after
</form>
</tr>
then add input hidden after formname "Delete"
<td>
<?php echo "<input name='Switch' type='submit' id='Switch' value='Switch state ".$row['id']."'>"; ?></td>
<td><?php echo "<input name='Delete' type='submit' id='Delete' value='Delete mote ".$row['id']."'>"; ?></td>
<input name='id' type='hidden' value="<?php echo $row['id']; ?>">
<input name='state' type='hidden' value="<?php echo $row['state']; ?>">
and the last replace this:
<?php
if($_REQUEST['Delete']=='Delete mote ' . $row['id']) {
{
$sql3="DELETE FROM $table WHERE id=".$row['id'].";";
$result3=$conn->query($sql3);
header('Location: table.php');
}
}
if($_REQUEST['Switch']=='Switch state ' . $row['id']) {
{
if($row['state']=='1')
{
$sql2="UPDATE $table SET state='0' WHERE id=".$row['id'].";";
}
else
{
$sql2="UPDATE $table SET state='1' WHERE id=".$row['id'].";";
}
$result2=$conn->query($sql2);
header('Location: table.php');
}
}
?>
With this
<?php
if (!empty($_REQUEST['Delete']) && !empty($_REQUEST['id']))
{
$sql3="DELETE FROM $table WHERE id=".$_REQUEST['id'].";";
$result3=$conn->query($sql3);
echo '<script> location.replace("index.php"); </script>';
}
if (!empty($_REQUEST['Switch']) && !empty($_REQUEST['id']) && isset($_REQUEST['state']))
{
var_dump($_REQUEST['Switch']);
if($_REQUEST['state'] == '1')
{
$sql2="UPDATE $table SET state='0' WHERE id=".$_REQUEST['id'].";";
}
else
{
$sql2="UPDATE $table SET state='1' WHERE id=".$_REQUEST['id'].";";
}
$result2=$conn->query($sql2);
echo '<script> location.replace("index.php"); </script>';
}
?>
Im not say this is are the good solution. but it will solve your problem until you found the best solution.
After you do the delete, you instruct the browser to reload the page with this:
header('Location: table.php');
However, you can't send HTTP headers after you've started sending the data. You'll probably see an error message below your table somewhere stating "headers already sent".
You need to move your output of page content to after the last time you modify the response headers with the header() function, or use output buffering.
Just try cleaning the result array after the deletion query but before redirecting by using: unset($row); & also clean $result by initiating it: $result='';
Modified the code as below & added four lines into it on top two & at the bottom two with comments:
<form action="logout.php" method="post">
<input type="submit" name="logout" value="logout">
</form>
<b>Alarm Monitoring</b>
<p>Sensors state table. Clicking on "Switch state" will switch the field "state" of the associated mote. </p>
<p>State 1 means that the mote is active, the alarm will be activated if the mote is moved or if someone is detected.</p>
<p>State 0 means that the mote is inactive, the alarm will NOT be activated if the mote is moved or if someone is detected.</p>
<?php
$servername="localhost";
$username="root";
$password="patate";
$dbname="testbase";
$table="matable";
$conn = new mysqli($servername,$username,$password,$dbname);
if ($conn->connect_error) {
echo "kaput";
die("Connection failed: " . $conn->connect_error);
}
$row=array(); //Initialize the empty array (By shashi).
$result=''; //Initialize the empty result var (By shashi).
$sql="SELECT * FROM $table;";
$result=$conn->query($sql); ?>
<table border=0>
<tr>
<td>
<table border=1>
<tr>
<td width=150>ID</td>
<td width=150>Date</td>
<td width=300>PIR</td>
<td width=150>Accel</td>
<td width=100>State</td>
<td width=150>Switch</td>
<td width=150>Delete</td>
</tr>
<?php
while($row = $result->fetch_assoc()) : ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['pir']; ?></td>
<td><?php echo $row['accel']; ?></td>
<td><?php echo $row['state']; ?></td>
<form name="form1" method="post" action=''>
<td><?php echo "<input name='Switch' type='submit' id='Switch' value='Switch state ".$row['id']."'>"; ?></td>
<td><?php echo "<input name='Delete' type='submit' id='Delete' value='Delete mote ".$row['id']."'>"; ?></td>
</form>
</tr>
<?php
if($_REQUEST['Delete']=='Delete mote ' . $row['id']) {
{
$sql3="DELETE FROM $table WHERE id=".$row['id'].";";
$result3=$conn->query($sql3);
unset($row); //Clear the array (By shashi).
result=''; //Clear result Var (By shashi).
header('Location: table.php');
}
}
if($_REQUEST['Switch']=='Switch state ' . $row['id']) {
{
if($row['state']=='1')
{
$sql2="UPDATE $table SET state='0' WHERE id=".$row['id'].";";
}
else
{
$sql2="UPDATE $table SET state='1' WHERE id=".$row['id'].";";
}
$result2=$conn->query($sql2);
header('Location: table.php');
}
}
?>
<?php endwhile; ?>
</table>
</table>
</td>
</tr>
</table>
$sql="SELECT * FROM $table;"
should be after
$sql3="DELETE FROM $table WHERE id=".$row['id'].";";
and ather actions like update ...
looks like its deleted but you see old data :)
<?php
$servername="localhost";
$username="root";
$password="patate";
$dbname="testbase";
$table="matable";
$conn = new mysqli($servername,$username,$password,$dbname);
if ($conn->connect_error) {
echo "kaput";
die("Connection failed: " . $conn->connect_error);
}
if($_REQUEST['Delete']) {
{
$sql3="DELETE FROM $table WHERE id=".(int)$_REQUEST['Delete'].";";
$result3=$conn->query($sql3);
}
}
if($_REQUEST['Switch']) {
{
$sql2="UPDATE $table SET state= IF (`state`, 0, 1) WHERE id=".(int)$_REQUEST['Switch'].";";
$result2=$conn->query($sql2);
}
}
$sql="SELECT * FROM $table;";
$result=$conn->query($sql); ?>
<form action="logout.php" method="post">
<input type="submit" name="logout" value="logout">
</form>
<b>Alarm Monitoring</b>
<p>Sensors state table. Clicking on "Switch state" will switch the field "state" of the associated mote. </p>
<p>State 1 means that the mote is active, the alarm will be activated if the mote is moved or if someone is detected.</p>
<p>State 0 means that the mote is inactive, the alarm will NOT be activated if the mote is moved or if someone is detected.</p>
<table border=0>
<tr>
<td>
<table border=1>
<tr>
<td width=150>ID</td>
<td width=150>Date</td>
<td width=300>PIR</td>
<td width=150>Accel</td>
<td width=100>State</td>
<td width=150>Switch</td>
<td width=150>Delete</td>
</tr>
<?php
while($row = $result->fetch_assoc()) : ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['pir']; ?></td>
<td><?php echo $row['accel']; ?></td>
<td><?php echo $row['state']; ?></td>
<form name="form1" method="post" action=''>
<td><?php echo "<input name='Switch' type='submit' id='Switch' value='".$row['id']."'>"; ?></td>
<td><?php echo "<input name='Delete' type='submit' id='Delete' value='".$row['id']."'>"; ?></td>
</form>
</tr>
<?php endwhile; ?>
</table>
</table>
</td>
</tr>
</table>
And please do not use in this case some SQL queries in WHILE loop
This is very simple issue because I encounter with them, problem is SQL statement, you need look at MYSQL, so I resolve with this for example :
DELETE FROM `reyler` WHERE `reyler`.`id`=".$id_post1 ."";
this symbol you need => `` it is not this " or this '
second you can delete from mysql and mysql before deleting show you window with sql statement you can copy from there right statement,this is associated with your database in your hosting or in xampp server, I think will help you.))

multiple arrays value fetching with session

Insert Is Fine But if I select this value from database All Values are fine but single values fetch array problem I don't know how to solve this task. Please Update this code asap.
This Is Insert Code .....
<?php
if(isset($_POST['sendmessage'])){
$entermessage = $_POST['teachermessage'];
$checkbox_user = $_POST['usernameallcheckbx'];
$arr = implode(',',$checkbox_user);
//$arr2 = explode(',',$arr);
$insert = mysql_query("INSERT into usermessages(fromteacher,toparent,messages) VALUES('".$_SESSION['username']."','$arr','$entermessage')");
if($insert == 1){
echo "<h1>successful</h1>";
}
else{
echo mysql_error();
}
}
?>
<form method="post">
<div style="float:left; width:450px;"><br/><br/>Message: <br/>
<textarea style="width:400px; height:300px;" name="teachermessage"></textarea><br/>
<input type="submit" value="Send" name="sendmessage" /></div>
<div style="float:left; with:200px; padding-top:55px;">
<table>
<tr>
<?php
$select_query1 = mysql_query("SELECT * FROM register_user WHERE teacher='$teachername'");
while($chckbx=mysql_fetch_array($select_query1))
{
?>
<td><?php echo "<input type='checkbox' name='usernameallcheckbx[]' value=". $chckbx['userid']." />"; ?></td>
</tr>
<tr>
<td><?php echo $chckbx['parent_fname']." ".$chckbx['parent_lname']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</form>
And This Is Select Code....
<h2>Messages</h2>
<?php
$select_query3 = mysql_query("SELECT * FROM usermessages");
$fetch= mysql_fetch_array($select_query3);
$data=$fetch['toparent'];
$arr=explode(',',$data);
//$userids=explode(',',$data);
$sessionshow=$_SESSION['userid'];
$userids=in_array("$sessionshow",$arr);
$select_query2 = mysql_query("SELECT * FROM usermessages WHERE toparent in ('$userids')='".$_SESSION['userid']."'");
?>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<th>Teacher Name</th>
<th>Message</th>
</tr>
<?php
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo "<tr>";
echo "<td>".$fetch_data=$fetch_name2['fromteacher']."</td>";
echo "<td>".$fetch_data=$fetch_name2['messages']."</td>";
echo "</tr>";
}
?>
</table>
I have only put this as an answer to show some incorrect code - remove fetch data from your loop as it doesn't do anything
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo "<tr>";
echo "<td>".$fetch_name2['fromteacher']."</td>";
echo "<td>".$fetch_name2['messages']."</td>";
echo "</tr>";
}
even better is use of a HEREDOC:
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo <<<EOF
<tr>
<td>{$fetch_name2['fromteacher']}</td>
<td>{$fetch_name2['messages']}</td>
</tr>
EOF;
}
I really can't figure out what you're trying to do, but maybe this is the query you want:
SELECT * FROM usermessages WHERE FIND_IN_SET('$sessionshow', toparent)
FIND_IN_SET(str, strlist) searches the comma-separated list in strlist for an element that equals str, and returns the position in the list; if it's not found it returns 0, which counts as false.
I can't see any purpose to any of the code that uses $select_query3.

how to parse the contents of a particular row of a html table into array

I need to pass a one of these row contents of features-table to an array. But the problem is I used an iframe to display the table. And I need it to happen when after clicking the image of particular row.
In main.php
<iframe id="ifrm" src="reserved_tables/reserved_rooms_table.php"></iframe>
In reserved_rooms_table.php
<?php
include '../core/init.php';
$username = $user_data['username'];
$que = "SELECT * FROM ordered_rooms WHERE `username` LIKE '$username'";
$reslt = mysql_query($que);
echo '<table class="features-table" >';
echo '<thead>
<tr>
<td></td>
<td>Date</td>
<td>Start At</td>
<td>End At</td>
<td>Action</td>
</tr>
</thead>
<tbody>';
while($row = mysql_fetch_array($reslt)){
echo '<tr><td>' . $row['room_name'] .' </td><td> '. $row['date'] . '</td><td>'. $row['s_at'].'hrs</td>
<td>'. $row['e_at'].'hrs</td><td><input type="image" src="../images/cross.png" onclick="delete();" value=""></td></tr>';
}
echo "</tbody></table>";
mysql_close(); //connection closed
?>
It isn't entirely clear what you're trying to do. If you want to take data from an HTML table row and send it to a PHP array after a click then you'll need to use javascript.
Keep it simple. Create a link that sends the data to whatever URL/file does the processing:
while ($row = mysql_fetch_array($reslt)) {
?>
<tr>
<td><?php echo $row['room_name'] ?></td>
<td><?php echo $row['date'] ?></td>
<td><?php echo $row['s_at'] ?>hrs</td>
<td><?php echo $row['e_at'] ?>hrs</td>
<td><a id="my_link" href="some_file.php?room_name=<?php echo $row['room_name'] ?>&date=<?php echo $row['date'] ?>&s_at=<?php echo $row['s_at'] ?>&e_at=<?php echo $row['e_at'] ?>"><input type="image" src="../images/cross.png" value=""><a/></td>
</tr>
<?php
}
The data will then be available to some_file.php in $_GET.
Note that you can still use javascript to process this dynamically. You could add a click function to the link, so that when it is clicked, it does an AJAX call using the href value. For example:
$('#my_link').click(function() {
$.ajax({
url: this.href
});
});

Getting the value from first cell in a row to submit using Javascript

I create a table using PHP from a database, meaning the size of the table and values vary.
The table creation:
<table>
<thead>
<tr>
<th>Ticket</th>
<th>Empresa</th>
<th>Requerente</th>
<th>Motivo</th>
<th>Data</th>
<th>Hora</th>
</tr>
</thead>
<tbody>
<form name="goTicket" action="resolver.php" method="POST" >
<?php
$sql = "QUERY";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<tr onmouseover=\"this.style.background='#EFF5FB';this.style.cursor='pointer'\"
onmouseout=\"this.style.background='white';\" onclick=\"javascript: submitform()\">";
echo "<td>$row[Ticket]</td>";
echo "<input type='hidden' name='_ticket' value='$row[Ticket]' />";
echo "<td>$row[Empresa]</td>";
echo "<td>$row[Requerente]</td>";
echo "<td>$row[Motivo]</td>";
echo "<td>$row[Data]</td>";
echo "<td>$row[Hora]</td>";
echo "</tr>";
}
echo "</form>";
echo "<tr><td colspan='6' style='text-align: center;'><form action='adminmenu.php' ><br /><input type='submit' name='woot' value='Main Menu' /></form></td></tr>";
echo "<tbody>";
echo "</table>";
?>
The Javacript function used to submit is this one:
<script type="text/javascript">
function submitform()
{
document.forms["goTicket"].submit();
}
</script>
Now whenever I click on a row it takes to the appropriate page "resolver.php" but always sends the most recent data, from last time the while was executed.
I need the value from the first cell, or the hidden input tag, that contains what I need, from the row I click.
Thank you.
Full suggestion
<script type="text/javascript">
function submitform(ticket) {
document.goTicket.elements["_ticket"].value=ticket;
document.goTicket.submit();
}
</script>
<table>
<thead>
<tr>
<th>Ticket</th>
<th>Empresa</th>
<th>Requerente</th>
<th>Motivo</th>
<th>Data</th>
<th>Hora</th>
</tr>
</thead>
<tbody>
<form name="goTicket" action="resolver.php" method="POST" >
<input type="hidden" name="_ticket" value="" />
<?php
$sql = "QUERY";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<tr onmouseover="this.style.background='#EFF5FB';this.style.cursor='pointer'"
onmouseout="this.style.background='white';"
onclick="submitform('<?php echo $row[Ticket]; ?>')">
<td><?php echo $row[Ticket]; ?></td>
<td><?php echo $row[Empresa]; ?></td>
<td><?php echo $row[Requerente]; ?></td>
<td><?php echo $row[Motivo]; ?></td>
<td><?php echo $row[Data]; ?></td>
<td><?php echo $row[Hora]; ?></td>
</tr>
<?php } ?>
</form><!-- not really nice -->
<tr><td colspan="6" style="text-align: center;"><form action="adminmenu.php" >
<br /><input type="submit" name="woot" value="Main Menu" /></form></td></tr>
</tbody>
</table>
Your problem is that you're just submitting the form without any reference to what was clicked. All the hidden inputs have the same name so the form just sends the last one.
Try the following:
echo "<tr onmouseover=\"this.style.background='#EFF5FB';this.style.cursor='pointer'\" onmouseout=\"this.style.background='white';\" onclick=\"javascript: submitform('$row[Ticket]')\">";
// delete this from while:
// echo "<input type='hidden' name='_ticket' value='$row[Ticket]'/>";
// and instead add before </form> with value=""
Then change your javascript to change the value before submitting:
function submitform(val) {
document.forms["goTicket"].elements["_ticket"].value = val;
document.forms["goTicket"].submit();
}
Kudos to mplungjan also got this as I was typing!
If I see good ... Yo set form with many of hidden inputs with same name ... what you want with this... of course it return last value ...
you have to changing names in loop and then call exact name of input

Categories