Why does my submit button fail to call php function? - php

I have a very simple php site that and am attempting to make it a little more dynamic. Previously, I required user to click on a link to open a new page containing several images together with some 'submit' buttons. Pressing a button called a php file that saved some information in a text box. This was working fine. However, I have now made the content a little more dynamic so that the user chooses an item from a popupmenu to update content in the same page. However, now the submit buttons produced dynamically do not seem to work. I am quite new to web development generally so not sure why this should be the case. Any help much appreciated.
This is the index.php file that populates the list box and sets up the page to dynamically manage the content.
'''php
<!doctype html>
<html>
<head>
<script>
function showImages( imageDate ) {
if ( imageDate == "") {
document.getElementById("imageTable").innerHTML ="";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 ) {
document.getElementById("imageTable").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "dispData.php?imageDate="+imageDate, true );
xmlhttp.send();
}
}
</script>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Title</title>
<meta name="language" content="en" />
<meta name="description" content="" />
<meta name="keywords" content="" />
</head>
<body>
<?php
$myDirectoryStr = "trialImages/";
// open this directory
$myDirectory = opendir($myDirectoryStr);
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// sort into date order
sort( $dirArray );
// close directory
closedir($myDirectory);
// count elements in array
$indexCount = count($dirArray);
?>
<?php
// loop through the array of files and print them all in a list
$cnt = 0;
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -10);
// start new row of table
if ($extension == 'tempIm.png'){
$dateStr[$cnt] = substr($dirArray[$index], 0, 8 );
$cnt++;
}
}
// count elements in array
$indexCount = count($dateStr);
// find unique dates
$dateStrUnique = array_values( array_unique( $dateStr, SORT_STRING ) );
// count elements in array
$indexCount = count($dateStrUnique);
echo '<form>';
echo '<select name="dates" onchange="showImages(this.value)">';
echo '<option value="">select date ...</option>';
for($index=0; $index < $indexCount; $index++) {
echo '<option value="' . $dateStrUnique[$index]. '">' . $dateStrUnique[$index] . '</option>';
}
echo '</select>';
echo '</form>';
?>
<br>
<div id="imageTable"><b> image information will be displayed here ... </b></div>
</body>
</html>
'''
This is the dispData.php file that produces the dynamic content used to update the div tag and containing the submit buttons and images
'''php
<?php
// recover some information
$imageDateTarget = $_GET['imageDate'];
// image directory
$myDirectoryStr = "trialImages/";
// open directory
$myDirectory = opendir($myDirectoryStr);
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// sort into date order
sort( $dirArray );
// close directory
closedir($myDirectory);
//count elements in array
$indexCount = count($dirArray);
echo '<table class="fixed">
<col width="200px">
<col width="200px">
<col width="100px">';
// loop through the array of files and display them in table
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -10);
// start new row of table
if ($extension == 'tempIm.png'){ // input image place in first column
// image date
$imageDate = substr($dirArray[$index], 0, 8 );
// if image date the same as selected date then display image
if ( strcmp( $imageDateTarget, $imageDate ) == 0 ) {
echo '<tr>';
echo '<td>' . $dirArray[$index] . '</td>';
echo '</tr>';
echo '<tr>';
echo '<td height=400><img src="' . $myDirectoryStr . $dirArray[$index] . '" class="rotate90" " alt="Image" border=3 height=200 width=400></img></td>';
echo '<form action="writeNotes.php" method="POST">';
//search for matching image notes if they exist and display
$indexImageNotes = array_search( $imageDate . 'notes.txt', $dirArray );
if ($indexImageNotes){
$notes = file_get_contents($myDirectoryStr . $imageDate . 'notes.txt'); // read contents into string
echo '<td><textarea name = "notes" rows = "26" cols="30">' . $notes . '</textarea></td>';
}
else {
echo '<td><textarea name = "notes" rows = "26" cols="30">add some comments here ...</textarea></td>';
}
echo '<td><input type = "submit"></input><input type = "hidden" name = "imageDate" value = "' . $myDirectoryStr . $imageDate . '"></input></form></td>';
echo '</tr>';
}
}
}
?>
'''
And this is the writeNotes.php function that saves the text notes and should be called when the submit buttons are pressed
'''php
<?php
print_r("I am here");
$file = $_POST["imageDate"] . 'notes.txt';
$data = $_POST["notes"];
file_put_contents($file, $data);
?>
'''
Part of the problem is that I don't get any error messages, just a failure to execute the writeNotes.php function

I think there must be some mistakes in my earlier code as I have attempted a further simplified version and this seems to work. I simply populate a popupmenu below
'''php
<!doctype html>
<html>
<head>
<script>
function showImages( imageDate ) {
if ( imageDate == "") {
document.getElementById("imageTable").innerHTML ="";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 ) {
document.getElementById("imageTable").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "dispData.php?imageDate="+imageDate, true );
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="dates" onchange="showImages(this.value)">
<option value="">select date ...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
<br>
<div id="imageTable"><b> information will be displayed here ... </b></div>
</body>
</html>
'''
And return the dynamic content here
'''php
<?php
echo '<form action="writeNotes.php" method="POST">
<td><input type = "submit"></input><input type = "hidden" name = "imageDate" value = "a_value"></input></form></td>';
?>
'''
And the writeNotes.php function
'''php
<?php
$file = $_POST["imageDate"];
print_r($file);
//header("Location: index.php"); //note there must be no output before using header
?>
'''
This seems to work without a problem. Apologies for asking the earlier question and thanks again for comments.

Related

autocomplete does not display accurate answer it displays all options

I have a page where i have to display district drop down on selection of state dropdown. and then display postoffices dropdown on selection of distirict dropdown. then a autocomplete places input box on selection of postoffice dropdown.
i completed it successfully. but the autocomplete input box of places does not display options as per entered keywords, weather it displays all options what ever keyword is entered.
below is my php page :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="js/jquery-ui.css">
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
$r = file('app_data/in.txt');
$states = array();
foreach($r as $value){
$x = explode("\t",$value);
//$india[] = array('pin'=>$x[1], 'place' => $x[2], 'state' => $x[3], 'dist' => $x[5] );
$states[] = $x[3];
}
$states = array_unique($states);
sort($states);
echo '<select id="state">';
foreach($states as $state){
echo "<option> $state </option>";
}
echo '</select>';
foreach($_POST as $post){
echo $post;
}
echo '<select id="dist">';
echo '</select>';
echo '<select id="postoffice">';
echo '</select>';
?>
<script>
$('#state').focusout(function (){
$.get('func-get-dist.php',{'state' : $(this).val()},function(data){
$('#dist').html(data);
});
});
$('#dist').focusout(function (){
$.get('func-get-dist.php',{'state' : $('#state').val(),'dist' : $(this).val()},function(data){
$('#postoffice').html(data);
});
});
$('#postoffice').focusout(function (){
var postoffice = $(this).val();
$('#tags').autocomplete({
source : ("func-get-dist.php?postoffice="+postoffice),
});
});
</script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
<div id="test">
<div id="test1">
</div>
</body>
</html>
below is my html-get-dist.php page :
<?php
if(isset($_GET['postoffice']) && !empty($_GET['postoffice'])){
$postoffice = $_GET['postoffice'];
$r = file('app_data/in.txt');
$places = array();
foreach($r as $value){
$x = explode("\t",$value);
if(strtolower($x[7]) == $postoffice){
$places[] = strtolower(trim($x[2]));
}
}
$places = array_unique($places);
sort($places);
echo json_encode($places);
}elseif(isset($_GET['state']) && !empty($_GET['state'])){
if(isset($_GET['dist']) && !empty($_GET['dist'])){
$state = $_GET['state'];
$dist = $_GET['dist'];
$r = file('app_data/in.txt');
$posts = array();
foreach($r as $value){
$x = explode("\t",$value);
if(($x[3] == $state) && ($x[5] == $dist)){
//echo $x[6].'-'.$x[7].'-'.$x[8].'<br>';
$posts[] = $x[7];
}
}
$posts = array_map('strtolower',$posts);
$posts = array_unique($posts);
sort($posts);
foreach($posts as $postoffice){
echo '<option>'.$postoffice.'</option>';
}
}else{
$state = $_GET['state'];
$r = file('app_data/in.txt');
$dists = array();
foreach($r as $value){
$x = explode("\t",$value);
if($x[3] == $state){
$dists[] = $x[5];
}
}
$dists = array_unique($dists);
sort($dists);
foreach($dists as $dist){
echo '<option>'.$dist.'</option>';
}
}
}
?>
You compare the userinput with the entire value, try to do the comparison with the same number of characters as the user entered:
foreach($r as $value){
$x = explode("\t",$value);
$charCount = strlen($postoffice);
if(strtolower(substr($x[7], $charCount)) == strtolower($postoffice)){
$places[] = strtolower(trim($x[2]));
}
}
Edit: It took me some time to figure it out but I think I have solution. There are 2 mistakes in your code:
in js you get the value of the select with var postoffice = $(this).val();, but .val() returns the selected index of the selectbox, not the selected text.
you compare the selected postoffice with $x[7], this is the 8th tab separated column in you data, if my count is correct you only have 7 columns there.
So my guess is that here you compare undefined with 0 and that returns true:
if(strtolower($x[7]) == $postoffice){
To solve this get the value in js like this:
var postoffice = $("option:selected", this).text();
... and use the correct index in the php comparison.

Call function php uing jquery

Hello i want to call a function using jquery. I tried a lot of ways and I can't get it.
This my principal webpage.
I'am uploading a file csv and pressing 'Crear' button, it uplaod the file while call the function.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<SCRIPT type="text/javascript">
$(function (){
$('#btnxml').click(function (){
alert("aki");
$('#contenidos').load('csv.php');
});
});
</SCRIPT>
</head>
<body>
<form action="index.php" id="filecsv" method="post" enctype="multipart/form-data">
<input type="file" multiple="multiple" id="file" name="up_csv[]"/>
<input type="submit" value="Cargar" name="btnxml" id="btnxml" /><br />
</form>
<?php
global $archivocsv;
//tipos de archivos permitidos
$extensionxml = array('csv','txt');
//destino
$rutaupcsv = './csv/';
//multicargador de archivos
$vt=0;
for($i=0;$i<count($_FILES['up_csv']['size']);$i++){
for ($j=-1; $j<count($extensionxml); $j++) {
if (strripos($_FILES['up_csv']['name'][$i], $extensionxml[$j])!== false) {
$filename = 'lista';
$destino = $rutaupcsv.$_FILES['up_csv']['name'][$i];
$archivocsv = basename($_FILES['up_csv']['name'][$i]);
move_uploaded_file($_FILES['up_csv']['tmp_name'][$i],$destino);
$vt=$vt+1;
break;
}
$ns=1;
}
}
?>
<div id="contenidos"></div>
csv.php
<?php
echo '<html>';
echo '<head>';
echo '<meta content="text/html;charset=utf-8" http-equiv="Content-Type">';
echo '<meta content="utf-8" http-equiv="encoding">';
echo '</head>';
function makecsv() {
global $archivocsv;
$csv = './csv/' . $archivocsv;
$doc = new DOMDocument();
$row = 1;
$handle = fopen($csv, "r");
# Rows Counter
$csvxrow = file($csv);
$csvxrow[0] = chop($csvxrow[0]);
$anzdata = count($csvxrow);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
#Load Predefined XML Template
$xml2 = $xml;
$xmlruta = './Templates/';
$xml = $xmlruta.$data[1].'.xml';
$doc->load($xml);
$xp = new DOMXPath($doc);
for ($c=0; $c < $num; $c++) {
foreach($xp->query('/ROOT/HEADER/#KEY[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[0];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#AUFNR[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[0];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#MATNR[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[1];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#GAMNG[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[2];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1AFFLL/E1FVOL/#MGVRG[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[2];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#GSTRS[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[3];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#GLTRS[. != ""]') as $attrib)
{
$fecha = new DateTime($data[3]);
$fecha->add(new DateInterval('P1M'));
$attrib->nodeValue = $fecha->format('Y-m-d');
}
}
$name = $data[0] .'-'. $data[1];
$doc->formatOutput = true;
echo $doc->saveXML();
$rutafinal = './XML/';
$doc->save($rutafinal.$name.'.xml');
}
fclose($handle);
echo $anzdata . " XML Creados" . "<br />";
return $data;
}
makecsv();
echo '</html>';
?>
I can't call the function.
it doesn't do anything when i try to call it.
EDIT: I think the problem is in my function. function edite
Javascript canĀ“t play with php directly because JS is client side (only in browser) and PHP is server side (only in browser). What you can do is a PHP file that has the code you want to invoke, and make JS call that page.
Separate the CVS code from the form and make JS call the new php with the CVS php functionality.
jQuery runs in the client's browser whereas your PHP is running on your web server. If you wish to call a PHP function from your jQuery code, your best option is to do so using AJAX.
You can find documentation for implementing an AJAX call in jQuery here: https://api.jquery.com/jQuery.ajax/
You'll need to print the actual hmtl to do the function.
PHP
<?php
print '<script> makecsv() </script>';
?>

PHP Search: Using Jquery to alter a php a value

I have a comics website. A feature it has is to allow users to search comics... the search will instantly parse the input and return thumbnail results based on matching title and keywords.
Originally, the search would return all of the results, and the bounding search box would expand infinitely downward, holding every single comic result. I thought it may be a nice touch to limit the results to 4, and display a message like "load 5 remaining images" if the user chooses to do so.
If they click on that message, I wanted limiting php variable to be removed or changed.
So far, it loads with the limit, and shows a link...
EDIT: Latest Code:
search_field.php (the search file that get's included on a page... this file calls search.php via JQuery):
<?php $site = (isset($_GET['site']) ? ($_GET['site']) : null); ?>
<div id="sidebar" class="searchborder">
<!--Allow users to search for comic-->
<!--<span class="search">Search for <?php// echo (($site == "artwork") ? 'artwork' : 'a comic'); ?> </span>-->
<script type="text/javascript">
function GetSearch(mySearchString){
$.get("./scripts/search.php", {_input : mySearchString, _site : '<?php echo $site ?>'},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
</script>
<center>
<table>
<tr>
<td>
<span class="search">
<img src="./images/SiteDesign/Search.png" />
<input type="text" onkeyup="GetSearch(this.value)" name="input" value="" />
<!--<input id="site" type="hidden" value="<?php// echo $site; ?>">-->
</span>
</td>
</tr>
</table>
</center>
<span id="output"> </span>
</div>
search.php, the file that's called to parse the string and return the results:
<?php
//Query all images:
include 'dbconnect.php';
$site = $_GET['_site'];
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : $site);
$start = (isset($_GET['_start']) ? ($_GET['_start']) : null);
echo "start: " . $start;
//if user goes to hittingtreeswithsticks.com... no "site" value will be set... so I need to set one
if ($site == null) {
$site = "comics";
}
if ($siteChoice == "artwork") {
$sql = "SELECT id, title, keywords, thumb FROM artwork";
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else if ($siteChoice == "comics") {
$sql = "SELECT id, title, keywords, thumb FROM comics";
$thumbpath = "./images/Comics/ComicThumbnails/";
}
else {
$sql = "SELECT id, title, keywords, thumb FROM $site";
if ($site == "artwork") {
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else {
$thumbpath = "./images/Comics/ComicThumbnails/";
}
}
/* For this to work, need all comics replicated in an "All Comics" file along with "All Thumbnails"
else {
$sql = "SELECT id, title, thumb FROM comics
UNION
SELECT id, title, thumb FROM artwork";
$thumbpath = "./images/AllThumbnails/";
}*/
$imgpaths = $mysqli->query($sql);
mysqli_close($mysqli);
$idresult = array();
$imgresult = array();
$thumbresult = array();
//CHECK IF $INPUT == IMAGE PATH
if (strlen($input) > 0)
{
while ($row = $imgpaths->fetch_assoc())
{
//query against key words, not the image title (no one will remember the title)
if (stripos($row['keywords'], $input) !== false || strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
//if (strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
{
array_push($idresult, $row['id']);
array_push($imgresult, $row['title']);
array_push($thumbresult, $row['thumb']);
}
}
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
if (count($imgresult) > $max) {
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo "<br/><i><a href='.?action=homepage&site=" . $siteChoice . "&start=4' class='loadSearch'>load " . $difference . " more result" . (($difference != 1) ? 's' : '') . "... </a></i>";
}
else {
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
}
echo "</ul>";
}
}
?>
<script type="text/javascript">
$(".loadSearch").click(function() {
//alert("Test");
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
});
</script>
Try this:
<script type="text/javascript">
$("#loadSearch").click(function() {
$.get('URL WITH QUERY', function(data) {
$('#results').html(data);
});
});
</script>
From what i get all you need is when "load more" is clicked only new results should be shown.
Load more has to be a url same as your search url.
Search/Autocomplete URL - example.com/autocomplete?q=xkd
Load More URL - example.com/autocomplete?q=xkd&start=4&max=1000
Just add two parameters to your url. start and max. Pass them to your queries and you get exact result.
Only verify Start < Max and are integers intval() and not 0 empty(). Also if Max <= 4 then dont show load more.
I would give all of your results back, then try to determine your results. If more then 4, loop out the first 4 results. If the user clicks on the load more button your start looping from your 4th element. That way you only need to hit the server once (per search).
Try to give back your results in json, so you can format it the way you like in your html file.
In pseudo code:
searchTerm = 'hello';
resultsFromServer = getResults($searchterm);
resultcounter = count(resultsFromServer);
if(resultcounter > 4)
loop 4 results
else
loop all results
$(".loadSearch").click(function(e) {
//alert("Test");
e.preventDefault();
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
I ended up going with jquery show and hide functions.
PHP Snippet:
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo '<div id="moreResults">';
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
echo '</div>';
if (count($imgresult) > $max) {
?>
<br />Load <?php echo $difference; ?> more result<?php echo (($difference != 1) ? 's' : ''); ?>...
<?php
}
echo "</ul>";
}
}
Jquery:
<script type="text/javascript">
$("#moreResults").hide();
$("#showMore").click(function() {
$("#moreResults").show();
$("#showMore").hide();
});

Using jQuery to load a PHP Page in a div

I have this script:
<script type='text/javascript' src='js/jquery-1.4.4.mi.js'></script>
<script type='text/javascript'>
$('.filterMonth').change(function(){
alert('ijijiji');
$.ajax({
url: 'ajax/filterMandays.php',
//type: 'GET',
success: function(data){
//data is returned back
$('#mandayTable').html(data);
}
});
});
</script>
and this html:
<select name ="filterMonth">
<?php
$array_month = array("January","February","March","April","May","June","July","August","September","October","November","December");
foreach($array_month as $key => $month)
{
$value_month = $key+1;
echo "<option value = '$value_month'>$month</option>";
}
?>
</select>
-
<select name = "filterYear" onChange = "filter(filterMonth.value, filterYear.value)">
<?php
$curYear = date('Y');
for($i = 1990; $i<=$curYear+10; $i++)
{
if($i == $curYear)
{
echo "<option value = '$i' selected = 'selected'>$i</option>";
}
else
{
echo "<option value = '$i'>$i</option>";
}
}
?>
</select>
</td>
</tr>
</br>
</br>
<tr>
<div id="mandayTable"></div>
and this php page:
<?php
include("all.php");
$q = "SELECT md.mandays_id,md.employeenum,md.month,md.year,md.required_man_days,d.firstname,d.lastname
FROM tbl_mandays md,tbl_employee_details d
WHERE md.active = '1'
AND md.employeenum = d.employeenum
AND md.month = '10';";
$res = $db->Execute($q);
echo "<table border = 1>";
echo "<tr><th>Employee Number</th><th>First Name</th><th>Last Name</th><th>Month-Year</th><th>Required Man Days</th><th>Edit/Delete</th></tr>";
while($rows = $res->FetchRow())
//for($i=0;$i<5;$i++)
{
//iterating through // check if employee
// // if(isset($row[])) { }
$mandays_id = $rows[0];
$empnum = $rows[1];
$month_year = $rows[2] ."-" .$rows[3];
$required_man_days = $rows[4];
$firstname = $rows['month'];
$lastname = $rows[6];
//echo approvers here are not taken
//<a href=\"view_team.php?id=".$empnum."\" -> for someone to view the people beneath them (like org tree)
echo "<tr><td>".$empnum . "</td><td>".$firstname ."</td><td>".$lastname ."</td><td>" . $month_year ."</td><td>" .$required_man_days . "</td><td width = \"200\" align = \"center\"><a href = 'edit_mandays.php?mandays_id=$mandays_id');'>Edit/Delete</a></td></tr>";
}
echo "</table>";
?>
the script should basically load the php page in the div in the html once the "filterMonth" has been changed. but it doesn't work.
what seems to be the problem? :(
The selector in your jQuery is $('.filterMonth') but your select box doesn't have the filterMonth class. You need to change it to $('select[name=filterMonth]').
In order for the jQuery selector to contain your select, you need to make sure that it runs after the Select element is in the DOM (ie: lower down the HTML), or run your JavaScript once the document has finished loading, for example:
<script type='text/javascript' src='js/jquery-1.4.4.mi.js'></script>
<script type='text/javascript'>
jQuery(function() {
// do your DOM selections here, this function only runs once the document is loaded
});
</script>

Able to have div encompass part of table?

I'm making a table of games and times but I want to use javascript to show/hide part of the list. Once 5 games have been listed, all the games following that are to be encompassed within the div that will be showed/hidden by hitting a button. The trouble is, my div does not encompass ANY of the rows of the table, which is weird because the code says otherwise.
Am I not allowed to make a div that encompasses part of a table?
Thanks as always.
<table>
<?php
$result = #mysql_query('QUERY REMOVED');
$rows = mysql_num_rows($result);
$count = 0;
if ($rows == 0) {
echo '<h3> No games on this day </h3>';
} else {
while ($row = mysql_fetch_array($result)) {
**a bunch of variable assignments**
if($count == 5) echo '<tbody class="moreLess">';
echo '<tr><td>' . $awayteam . ' # ' . $hometeam . '</td><td>' . $time . '</td></tr>';
$count++;
}
if($count >= 6) echo '</tbody>';
}
?>
</table>
<div class="moreLessSwitch"><span>More [+]</span></div>
In case you wanted it, the javascript I use (tested and working)
$(function() {
$(".moreLess").hide();
$(".moreLessSwitch").toggle(function() {
$(this).html("<span>Less [-]</span>");
$(this).prevAll(".moreLess").slideDown();
}, function() {
$(this).html("<span>More [+]</span>");
$(this).prevAll(".moreLess").slideUp();
});
});
The table output HTML: http://pastebin.com/raw.php?i=99iUYq6j
No, a div can't exist between the table and tr tags.
However, you can (and should) use a tbody to delineate groups of tr.
Check out this fiddle.
[edit]
New fiddle.
tbody is correct way to define group of rows...
This test code works for me:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="../jquery/jquery.js"></script>
<script type="text/javascript">
$(function(){
$(".moreLess").hide();
$(".moreLessSwitch").toggle(function() {
$(this).html("<span>Less [-]</span>");
$(".moreLess").slideDown();
}, function() {
$(this).html("<span>More [+]</span>");
$(".moreLess").slideUp();
});
})
</script>
</head>
<body>
<table>
<?php
$rows = array(array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3));
$count = 0;
if ($rows == 0) {
echo '<h3> No games on this day </h3>';
} else {
while ($row = array_pop($rows)) {
//**a bunch of variable assignments**
if($count == 5) echo '<tbody class="moreLess">' . "\r\n";
echo '<tr><td>' . $awayteam . ' # ' . $hometeam . '</td><td>' . $time . '</td></tr>' . "\r\n";
$count++;
}
if($count >= 6) echo "</tbody>\r\n\r\n";
}
?>
</table>
<div class="moreLessSwitch"><span>More [+]</span></div>
</body>
</html>
Your HTML is invalid. A <div> cannot occur inside a <table> unless inside a <td> cell, while yours spans several <tr> rows. A better solution would be to assign the .moreLess class to the table rows:
<tr class='moreLess'>
Your jQuery function then slides the table rows in and out of view.

Categories