I have a php page that will grab data from an SQL database and print it into a table, now if certain rows from the database have a certain parameter, a hidden row is inserted below that with a button to expand the row. This all works fine and I can query it with ajax into a div on a different page, but if someone were to expand the hidden row (with jquery) and the ajax update timer were to come along, it would reset and hide that row.
Here is the page that it is filled into and the ajax code to go with it:
<script type="text/javascript">
$(document).ready(function() {
$("#query").load("query.php");
var refreshId = setInterval(function() {
$("#query").load('query.php');
}, 5000);
$.ajaxSetup({ cache: false });
});
</script>
<div id="query"></div>
And from the query.php:
while($row = mysql_fetch_array($result))
{
$decoded = json_decode($row['B'],true);
$r = $decoded['r'];
$t = $decoded['t'];
$l = $decoded['l'];
$g = $decoded['g'];
$tp = (int)$t + 3;
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td align=\"center\"><font color=\"red\">[$t]</font></td>";
echo "<td align=\"center\"><font color=\"blue\">[$r]</font></td>";
echo(((int)$t != 0) ? '<td><button class="expand stylebutton">+</button>' : '<td>');
echo $row['Name_'] . "</td>";
echo "<td>" . $row['Date_'] . "</td>";
echo "<td>" . $row['IP'] . "</td>";
echo "<td>" . $row['G'] . "</td>";
echo "<td>" . $row['A'] . "</td>";
echo "<td>" . $row['Add'] . "</td>";
echo "<td>" . $row['Remove'] . "</td>";
echo "<td>" . $row['Comments'] . "</td>";
echo "</tr>";
if((int)$t != 0)
{
echo "<tr class=\"b\"style=\"display: none;\">";
echo "<td></td><td colspan=\"$tp\"><div style=\"color: #FC0;\"> Local:</div>";
foreach($l as $ll)
{
echo $ll . "<br>";
}
echo "<br><div style=\"color: #F00;\">Global:</div>";
foreach($g as $gg)
{
echo $gg . "<br> ";
}
echo "</td></tr>";
}
}
echo "</table>";
echo "<script type=\"text/javascript\">";
echo "$(document).ready(function() {
$(\".stylebutton\").click(function(){
$(this).parent().parent().next().toggle();
if($(this).text() == \"+\")
{
$(this).text('-');
}
else
{
$(this).text('+');
}
});
});
</script>";
Here's an image of what one of the rows looks like when expanded.
So basically I don't want the rows to contract when the ajax update rolls through, but instead just add more data on to the page. Thanks for any help!
You should have the php file return the data in json format to be used by your jQuery. Instead of replacing the html tags and causing your UI to retract, you will replace the data.
For Example
Your php code:
$data_array = array();
while($row = mysql_fetch_array($sql)) {
array_push( $row['some_row'] , $data_array ); // add the data to an array that will later be json encoded
}
echo json_encode($data_array);
jQuery
$.ajax({
url: 'query.php',
success: function(data) {
alert('This is the JSON: ' + JSON.stringify(data));
$('#selector').text(data.some_row); // place the data inside the element with id = 'selector'
}
});
Related
I'm creating a PHP web application in combination with SQL to order stuff. I'm randomly generating textboxes based on the amount of records I have. I want to pass the individual values to insert to the database. I want each cell to have a textbox in which I can input values and pass them with that cell. So if I want to order 2 of cell one I want to pass that value into a database.
Here's the code:
$i = 0;
if ($AanbodsTabel === false){
die(mysql_error());
}
while ($row = mysqli_fetch_array($AanbodsTabel)){
echo "<tr><td width = 4%>". htmlentities($row['Fustcode']) . "</td>";
echo "<td width = 8%>" . htmlentities($row['cultivar']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalFust']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalPerFust']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalStelen']) . "</td>";
echo "<td width = 4%><input type ='text' id='Bestelbox' value='' name='AantalBestellen".$i."'></td>";
echo "<td width = 6%>" . htmlentities($row['AantalFustBesteld']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalStelenBesteld']) . "</td>";
135: echo '<td width = 8%><a href="Home.php?aanbodid='. htmlentities($row['aanbodid']) .'&hoeveelheid='. $_GET["AantalBestellen$i"]. '"'
. ' class = "btnBestel">Bestel</a></td></tr>';
$i = $i + 1;
}
The error I'm getting is undefined index. I guess this is because the name isn't unique. But whatever I do I still get the error.
I'm getting:
undefined index: AantalBestellen0 on line 135;
you can use javascript for example
note i will bold the code you need, the rest is context.
note this is from a similar project of mine but you should get the point.
<div id="meldingen_top_div">
<?php
echo "<div class='alert_Top_Div_Left_Outer'>
<input type='submit' value='Openstaande Meldingen' class='btnLoad' name='' onclick='toggleThis(" . '"' . "#meldTableTop" . '"' . "), toggleThis(".'"'.".alert_Top_Div_Left_Inner".'"'.")'/>
<div class='alert_Top_Div_Left_Inner'>
<table class='tableRed' id='meldTableTop'><caption/><thead/><tfoot/><tbody>";
$sqlVII = "SELECT Meldingen.Melding_id, FORMAT(Meldingen.Melding_datum, 'dd-mM-yyyy') AS Melding_datum, Producten.Product_naam, Leveranciers.Leverancier_naam, Meldingen.Melding_notitie
FROM MovieWorld.dbo.Producten,
MovieWorld.dbo.Meldingen,
MovieWorld.dbo.Categorieen,
MovieWorld.dbo.Leveranciers
WHERE Producten.Product_id = Meldingen.Product_id AND Producten.Categorie_id = Categorieen.Categorie_id AND Categorieen.Leverancier_id = Leveranciers.Leverancier_id AND Producten.Product_actief = 1 AND Meldingen.Melding_actief = 1
";
$resV= $db->executeQuery($sqlVII);
$i=1;
if($resV!=FALSE){
while($arrx = sqlsrv_fetch_array($resV)){
Code wich is relevant for you:
echo "<tr>
<td><p class='meldDate'>{$arrx['Melding_datum']}</p></td>
<td>{$arrx['Product_naam']}</td>
<td>{$arrx['Leverancier_naam']}</td>
<td><input id='txt{$i} type='text' name='thisdoesntevenmatter' value='..'/></td>
<td><img src='somerandompath.png' onclick='getTxt(".'"txt{$i}"'.")'/></td>
</tr>"
$i=$i+1;
}
}else{}echo '</tbody></table></div></div>';
?>
</div>
and the Javascript function
function getTxt(id){
var tempId = document.getElementById(id).value;
return tempId;
}
however.. you can also send the value back into a php variable, OR use AJAX to pass it to an PHP class to insert it into the Database.
edit
Your quotes in line 135: seem incorrect. try this:
echo '<td width = 8%><a href="Home.php?aanbodid={htmlentities($row['aanbodid']) }&hoeveelheid={$_GET['AantalBestellen$i']}"'
. ' class = "btnBestel">Bestel</a></td></tr>';
Where you get undefined index? on that $_POST['AantalBestellen'] ?
Use
if (isset($_POST['AantalBestellen'])) { }
to identify that the post value has been set
same do later for the hoeveelheid:
if (isset($_GET['hoeveelheid'])) { }
echo-ing the input field:
echo "<td width = 4%><input type ='text' id='Bestelbox' value='" . $_GET['hoeveelheid'] . "' name='AantalBestellen'></td>";
Also, dont forget to clear the spaces in:
'&hoeveelheid = '. $_POST //near the =
I reading results from DB and i would like highlight (change color) by different value:
my reading function
{
...
...
echo "<td>" . $row['value1'] . "|</td>";
echo "<td>" . $row['value2'] . "|</td>";
}
and if value1 = 1 then all results in row is red if value1 =2 then this row is green etc?
it's posible to do with php or just javascript/jquery?
It's always better to use class attribute, because at this time you may want just change background color, but later also change color, font-size or anything...
my reading function
{
...
...
echo "<td class='custom-value1-{$row['value1']}'>" . $row['value1'] . "|</td>";
echo "<td class='custom-value2-{$row['value2']}'>" . $row['value2'] . "|</td>";
}
and css:
.custom-value1-1 {
background: lightblue;
...
}
.custom-value1-2 {
background: darkblue;
...
}
this way you make your work easier and clearer.
Yes you can do it like this:
my reading function //Change this to your loop or condition
{
...
...
$style = '';
switch($row['value1']){
case 1:
$style = 'background-color:#FF0000';
break;
case 2:
$style = 'background-color:#00FF00';
break;
}
echo "<tr style='". $style ."'>";
echo "<td>" . $row['value1'] . "|</td>";
echo "<td>" . $row['value2'] . "|</td>";
...
echo "</tr>";
}
I have question referring to the session in PHP.
I've coded in PHP for setting the session and I want to delete it , but I got some errors and confusing with using the UNSET(variable $_SESSION). Perhaps anyone could help me to show what should I do with this matter. Thanks in advance
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['index'] = 0
$_SESSION['chart'][0]['type'] = $type;
$_SESSION['chart'][0]['idanimal'] = $iddog;
$_SESSION['chart'][0]['price'] = $price;
printdata(); // <== this is the function to print out the data
All I want to do is just delete based on the index in this session
Here's the function :
function printdata()
{
$totalharga = 0;
if(is_array($_SESSION['chart']))
{
echo "<h3>"."Berikut adalah keranjang belanja anda" . "</h3>". "<br>";
$max = count($_SESSION['chart']);
$th1 = "<th>" . "No" . "</th>";
$th2 = "<th>" . "Animal Type" . "</th>";
$th3 = "<th>" . "ID Binatang" . "</th>";
$th4 = "<th>" . "Harga" . "</th>";
$th5 = "<th>" . "Hapus Data" . "</th>";
echo "<table border=1>";
echo "<tr>";
echo $th1 ;
echo $th2;
echo $th3;
echo $th4;
echo $th5;
echo "</tr>";
for ($indexo = 0; $indexo < $max; $indexo++)
{
echo "<tr>";
echo "<td>" . $indexo."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['type']."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['idanimal']."</td>";
echo "<td>" . "Rp. " . $_SESSION['chart'][$indexo]['harga']. ",-" ."</td>";
echo "<td>" . "<a href='deletesession.php?session=$indexo'>" ."Proses ". "</a>"."</td>";
$totalharga += $_SESSION['chart'][$indexo]['harga'];
echo "</tr>";
}
echo "</table>" . "<br/>";
echo "<blockquote>" . "Total Pembelian Item Yang Anda Pesan =". "<h2>". "Rp." . $totalharga . ",-" ."</h2>" . "</blockquote>";
}else
{
echo "Chart is still Empty";
}
}
I've already tried this :
Suppose that there is a chart already filled by the contents then I tried to delete within this code, I've received error with the unset variable
unset($_SESSION['chart'][1])
Thank you
I spot several things that could be improved in your code:
Don't echo in your functions, return instead (then echo what the function returns). This gives you more flexibility regarding what you do with your result.
PHP has a built-in loop for iterating arrays, the foreach loop. You should be using that instead of for.
So here's what I have:
function print_session_data($session) {
if (!is_array($session)) {
return "Array is empty";
}
$table_data = "";
$total_harga = 0;
foreach ($session as $index => $data) {
$table_data .= <<<TABLE_DATA
<tr>
<td>$index</td>
<td>{$data["type"]}</td>
<td>{$data["idanimal"]}</td>
<td>Rp. {$data["harga"]}</td>
<td>Proses</td>
</tr>
TABLE_DATA;
$total_harga += $data["harga"];
}
$result = <<<RESULT
<h3>Berikut abalah keranjang belanja anda</h3>
<table border="1">
<thead>
<tr>
<th>No</th>
<th>Animal Type</th>
<th>ID Binatang</th>
<th>Harga</th>
<th>Hapus Data</th>
</tr>
</thead>
<tbody>
$table_data
</tbody>
</table>
<blockquote>Total Pembelian Item Yang Anda Pesan = <strong>Rp. $total_harga</strong></blockquote>
RESULT;
return $result;
}
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['type'] = "Type";
$_SESSION['chart'][0]['idanimal'] = 6;
$_SESSION['chart'][0]['price'] = '$25';
$_SESSION['chart'][0]['harga'] = 25;
echo print_session_data($_SESSION["chart"]); // <== this is the function to print out the data
Suppose that there is a chart already filled by the contents then I
tried to delete within this code, I've received error with the unset
variable unset($_SESSION['chart'][1])
From what I can see from your code the best way to unset the data correctly is as follow:
DEMO.
You have to check if the $_SESSION['chart'][0] was set before using the session variable index again. If it $_SESSION['chart'] array still contains other indexes then you can call printdata(); else indicate that the session was empty.
I want to apply text-decoration:line-through to a table row which will be looped as per a mysql query. i want to strike out the row only if a variable's value is Not Interested
in the following loop there is a table row with id line. and there is a variable $status. I want the tabel row to get striked out if the value of $status comes "Not Interested" how can i do that?
while ($prow=mysql_fetch_object($productname))
{
$pname.=$prow->name.'<br />';
}
$staffname=mysql_query("select name from staff where sid='$assignedto' or flag='$assignedto'");
if(mysql_num_rows($staffname) > 1)
{
echo "<tr id='line'";
if($count %2==0)
echo "bgcolor='white' style='height:10px;'";
echo ">";
$count++;
?>
<td>
<span class="time"><a title="<?echo $added;?>" ></a></span>
</td>
<?
echo "<td >".$name. "</td>";
echo "<td>".$status."</td>";
echo "<td >".$phone." "."|"." ".$mobile. "</td>";
// echo "<td >".$email. "</td>";
echo "<td >".$city. "</td>";
echo "<td >".$pname. "</td>";
echo "<td >".$sname. "</td>";
echo "<td >".$lastactivity. "</td>";
?>
</table>
Something like this:
if ($status == 'Not Interested') { $strike = 'text-decoration:line-through'; }
else { $strike = ''; }
And then
echo "<tr id='line'";
if($count %2==0)
echo "bgcolor='white' style='height:10px; $strike'";
echo ">";
If $status is not 'Not Interested' it will simply add '' instead of text-decoration:line-through
Within the loop you can check the value of $status, and if it matches "Not Interested", you just add a specific CSS class(example: class="line-through") to that row, and you handle the rest in CSS like this:
tr.line-through td{
text-decoration:line-through
}
My problem is:
I'm trying to submit an array of hidden input types, which are stacked into an array using jquery onclick, to a PHP file. However, when I try to count or even echo the passed variable in the php file (saveTest.php), no data appears or the count variable is zero.
I've searched and I found this guy's question:
pass an array from jQuery to PHP (and actually go to the page after submit)
I think I'm close to the above post but I'm still a newbie in jQuery so I don't understand much of the codes.
This is my jquery:
$(function(){
$("td").click(function(){
if($(this).hasClass("on"))
{
alert("Already marked absent");
}
else
{
$(this).addClass("on");
var currentCellText = $(this).text();
$("#collect").append("<input type='text' hidden = '" + currentCellText + "'/>" + currentCellText);
}
});
$("#clicky").click(function(){
$("td").removeClass("on");
$("#collect").text('');
$("#collect").append("Absentees: <br>")
});
});
<?php
session_start();
include 'connectdb.php';
$classID = $_SESSION['csID'];
$classQry = "SELECT e.csID, c.subjCode, c.section, b.subj_name, e.studentID, CONCAT(s.lname, ', ' , s.fname)name
FROM ENROLLMENT e, CLASS_SCHEDULE c, STUDENT s, SUBJECT b
WHERE e.csID = c.csID
AND c.csID = '" . $classID . "'
AND c.subjCode = b.subjCode
AND e.studentID = s.studentID
ORDER BY e.sort;";
$doClassQry = mysql_query($classQry);
echo "<table id='tableone'>";
while($x = mysql_fetch_array($doClassQry))
{
$subject = $x['subj_name'];
$subjCode = $x['subjCode'];
$section = $x['section'];
$studentArr[] = $x['name'];
$studentID[] = $x['studentID'];
}
echo "<thead>";
echo "<tr><th colspan = 7>" . "This is your class: " . $subjCode . " " . $section . " : " . $subject . "</th></tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
for($i = 0; $i < mysql_num_rows($doClassQry); $i++)
{
if($i % 7 == 0)
{
echo "</tr><tr><td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
else
{
echo "<td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
}
echo "</tr>";
echo "</tbody>";
echo "</table>";
?>
This is my php file (saveTest.php)
<?php
$absent = $_POST['absent'];
//echo "absnt" . $absent[] . "<br>";
echo count($absent);
?>
Add name to hidden field:
$("#collect").append("<input type='hidden' name="absent[] value= '" + currentCellText + "'/>" + currentCellText);
It looks like you want to submit a javascript array to a php script and then make use of it. You can make use of .each() function to loop through all the hidden values and adding them into the array. Then use $.post to submit the array to a php script.
<script src="jquery.js"></script>
<script>
$(function(){
$('#btn_submit').click(function(){
var array_hidden = [];
$('input[type=hidden]').each(function(index){
var current_value = $.trim($(this).val());
array_hidden[index] = current_value;
});
$.post('arraysubmit.php', {'hidden_array' : array_hidden}, function(data){
$('#results').html(data);
});
});
});
</script>
<?php for($x=0; $x<=10; $x++){ ?>
<input type="hidden" name="name[]" value="Name<?php echo $x; ?>">
<?php } ?>
<input type="button" id="btn_submit">
<div id="results"></div>
You can then access the array in the php script using the post variable and do whatever you want with it:
$_POST['hidden_array']