Stay on current page after POST data - php

i have form which genrate from a specific search button.the newly generated form has several form wich can update it's own data
how to doing such a update without any affect to current page.
because of search result and search parameter should not be change.
eventually question in sort, give me an idea to "update each record based on query search while displaying it'.
ex:
<pre>
**name:[** k% **] branch:[** acc **] SEARCH** >>>>search form
EMPID | NAME | BRANCH | EDIT |
1 | kamal | acc | edit | >>>>>>dynamicaly generated form based query serch
2 | kapila | acc | edit | >>>>>>dynamicaly generated form based query serch
</pre>
thank you..
here my try
<?php
session_start();
include("../../config/config.inc.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="../../css/tbl.css"/>
<script type="text/javascript" src="../../jquery/formControll.js"></script>
<script type="text/javascript">
function autoSubmit(){
document.forms['searchForm'].action=SCRIPT_NAME;
document.forms['searchForm'].submit();
alert("done");
return true;
}
</script>
<title>OT Detail</title>
</head>
<body>
<?php
$errors = array();
$htmlcode="";
$me = $_SERVER['PHP_SELF'];
if(isset($_GET["invalid"])) //that means this is a redirected session
{
//form data default value initialization goes here
$Year=$_GET["Year"];
$Month=$_GET["Month"];
echo "<br><br><strong>ERROR: ";
foreach($_GET["errors"] as $k=>$v)
echo "<font color=red >".$v."</font>";
echo "</strong>";
}
else//if $_GET["invalid"] is not define then this is not redirecting session
{
//form data default value initialization goes here
$Year=date("Y");
$Month=date("m");
}
//for sequrity reasons we check weather 'REQUEST_METHOD'== 'POST'
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//server side manual form validation goes here
if (!$_POST['Year'])
$errors[0] = "Year ?";
if (!$_POST['Month'])
$errors[1] = "Month?";
if (count($errors)>0){
header("Location:setOtPermit.php?invalid=1&Year=".$_POST["Year"]."&Month=".$_POST["Month"]."&errors=".$errors);
exit;
}
else //no error
{
//get post array
foreach($_POST as $key=>$value){
if ($key!="Search"){
$value=htmlentities(stripslashes(strip_tags($value)));
${$key}=$value;
}//if $key
}//4e
//******* building sql for search
$sql="SELECT branch FROM ".$tbl_name2." WHERE empNo=".$_SESSION['resideFigure'];
$result=mysql_query($sql,$con)or die("cannot query");
$row=mysql_fetch_array($result,MYSQL_NUM);
$myBranch="Finance";//$row[0];
//echo $myBranch;
$sql="select * from ".$tbl_name4." e
where e.empNo in(
select d.empNo
from ".$tbl_name2." d
where d.branch='".$myBranch."') and e.empNo=000123 and e.permitMonth=1";
//echo $sql;
$result=mysql_query($sql,$con)or die("cannot query");
//*** search result feching into table goes here
if(mysql_num_rows($result)>0)
{
$htmlcode.="<center><table id='myDisplay'>";
$htmlcode.="<tr>";
for($i = 0; $i < mysql_num_fields($result); $i++) {
$htmlcode.="<th>".mysql_field_name($result,$i)."</th>";
}//for mysql_num_fields
$htmlcode.="</tr>";
$rowAlter=true;
while($row = mysql_fetch_assoc($result))
{
$htmlcode.="<form name='myform[]' method='POST' action='".$me."' onSubmit='return validateForm()'>";
if($rowAlter)
{$htmlcode.="<tr>";
$rowAlter=false;
}
else
{
$htmlcode.="<tr class='alt'>";
$rowAlter=true;
}
foreach($row as $k=>$v)
{
$htmlcode.="<td><input type='text' name='mydata[]' value='".$v."'></td>";
}//4e
$htmlcode.="<td><input type='submit' name='Update' onclick='autoSubmit()' value='Update'></td></tr>";
}//while
$htmlcode.="</form></table></center>";
}
else//when data not fetched
{
echo "<br><br><font color=blue >It seems to be you have not done any OT Permission!</font>";
}
}//else error count
}//if $_SERVER
?>
<center><form name="searchForm" method="POST" action="<?php echo strip_tags($me);?>" onSubmit="return validateForm()">
<table border="0" cellspacing="0" cellpadding="2">
<tr>
<td>Year</td><td><input type="text" name="Year" value="<?php echo $Year;?>"></td>
<td>Month</td><td><input type="text" name="Month" value="<?php echo $Month;?>"></td>
<td><input type="submit" name="Search" value="Search"></td>
<td><input type="reset" name="Reset" value="Reset"></td>
</tr>
</table>
</form></center>
<script type="text/javascript">SetHandlers()</script>
<?php
//display result as table
if (count($errors)==0)
echo $htmlcode;
//for sequrity reasons & confirm to dynamic form are submited we check weather 'REQUEST_METHOD'== 'POST'
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['Update'])){}
echo "if success i can do this its not difficult,but things is result desapper";
?>
</body>
</html>

I like to post the information back to the same page. You can use php to handle the post at the start of the script and then you already have all the data you submitted so you can populate the search field and everything using that data.
Alternatively don't submit the form but perform an ajax query. That way your current page remains unchanged.

Related

Re-populate fields after form submission and redirection PHP ONLY

I am supposed to have my form elements repopulate using php and html only after I click the link from page two. However, none of the fields are repopulating. Please help me!!?
Page 1:
<?php
session_start();
?>
<?php
/*
This page should:
1) Use a cookie (NOT PHP SESSION) that expires a year from now to do the following:
Record the timestamp of the FIRST load of this page (but NOT any subsequent load of this page).
Note: You only need first 3 parameters in setcookie() for this HW.
2) If the suvey was already completed, transfer to third page (thank you page).
That page instructs you to set a cookie that will allow you to detect this.
Recall from the CRUD example how page transfers are done in PHP:
header("Location: URL");
3) The form in this page should submit to THIS PAGE, and then transfer to hw_page2.php
after saving stuff to PHPs built-in $_SESSION superglobal.
The data will then be available in all the other pages (remember no database is allowed for this HW).
4) If the button in the 2nd page is clicked to come back to this page, the
Session data should re-populate into the form.
*/
if (!isset($_COOKIE['load_date'])) {
setcookie('load_date', time(), time() + (86400 * 365));
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h3><?=$message?></h3>
User Profile:
<?php
$load_date = $_COOKIE['load_date'];
$_SESSION['is_cool'] = $_POST['is_cool'];
$_SESSION['like_bands'] = $_POST['like_bands'];
$_SESSION['other_band'] = $_POST['other_band'];
$is_cool = $_SESSION['is_cool'];
$bands = $_SESSION['like_bands'];
$other_band = $_SESSION['other_band'];
print_r($bands);
echo $other_band;
echo $is_cool;
?>
<br><br>
<form action="hw_page1.php" method="POST" name="form1" onsubmit="return validate_form()">
<input type="hidden" name="task" value="process_profile">
<input type="checkbox" name="is_cool" value= "yes" <?php if ($is_cool == 'yes') {
echo 'checked = "yes"';
}?>>
Are you cool?
<br><br>
What Bands do you like?
<br>
<select name="like_bands[]" multiple> <small>* Required Field</small>
<option value="Sabbath" <?php if (isset($_SESSION['like_bands']) && in_array("Mastodon", $bands)) {
echo 'selected';
} ?>> Black Sabbath</option>
<option value="Mastodon" <?php if (isset($_SESSION['like_bands']) && in_array("Mastodon", $bands)) {
echo 'selected';
} ?> >Mastodon</option>
<option value="Metallica" <?php if (isset($_SESSION['like_bands']) && in_array("Metallica", $bands)) {
echo 'selected';
} ?> >Metallica</option>
<option value="Swift" <?php if (isset($_SESSION['like_bands']) && in_array("Swift", $bands)) {
echo 'selected';
} ?> >Taylor Swift</option>
</select>
<br><br>
Favorite band not in the above list.
<br>
<input type="text" name="other_band" value="<?=$other_band?>">
<br><br>
<button type="submit" name= 'submit' value = 'submit'> Continue/Confirm </button>
</form>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Client-side form validation
// Don't change the names of stuff in the form, and you won't have to change anything below
// Used built-in JS instead of JQuery or other validation tool
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function validate_form() {
var form_obj = document.form1;
var count_liked = 0;
for (var i=0 ; i < form_obj['like_bands[]'].options.length ; i++ ) {
if (form_obj['like_bands[]'].options[i].selected) {
count_liked++;
}
}
if (count_liked == 0) {
alert("You must choose a band from the menu.");
return false; // cancel form submission
}
return true; // trigger form submission
}
</script>
<?php
$_SESSION['is_cool'] = $is_cool;
$_SESSION['like_bands'] = $bands;
$_SESSION['other_band'] = $other_band;
echo $_SESSION['is_cool'];
if (isset($_SESSION['like_bands'])) {
header('Location: hw_page2.php');
}
?>
</body>
</html>
My second Page:
<?php
session_start();
/*
This page should:
1) Transfer back to hw_page1.php if loaded directly without the survey being completed (no survey data in session).
2) Display the Survey Data submitted from the previous page.
3) The form in this page should submit to THIS PAGE.
Use PHP to validate that the form below is completed.
Validate that the signature is not the empty string or only blank spaces (use PHP trim() function)
And of course validate that the checkbox was checked.
If the validation passes, save the signature into SESSION ande transfer to hw_page3.php.
If the validation fails, don't transfer.
Instead, back through to the form in this page WITH an appropriate message.
In that case, the Survey Data MUST also re-display in this page.
Note:
hw_page1.php used client-side JavaScript validation to ensure that all data was collected.
For the form below. do NOT use client-side JavaScript validation, but rather use PHP as instructed above.
Client-side validation is convenient for the end user, but can be bypassed by someone with know-how.
*/
?>
<?php
if (!isset($_SESSION['is_cool']) and !isset($_SESSION['like_bands'])) {
header('Location: hw_page1.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Verify Profile</title>
</head>
<body>
<?php
$is_cool = $_SESSION['is_cool'];
$bands = $_SESSION['like_bands'];
$other_band = $_SESSION['other_band'];
echo $is_cool;
print_r($bands);
echo $other_band;
$_SESSION['is_cool'] = $is_cool;
$_SESSION['like_bands'] = $bands;
$_SESSION['other_band'] = $other_band;
$bandslist = "";
foreach ($bands as $band) {
$bandslist .= "$band, ";
}
?>
<!-- Display Survey Data Here -->
<table width="" border="1" cellspacing="0" cellpadding="5">
<tr valign="top">
<td>Are you cool?</td>
<td>Liked Bands</td>
<td>Other Favorite Band</td>
</tr>
<tr valign="top">
<td><?= $_SESSION['is_cool']; ?></td>
<td><?= $bandslist; ?></td>
<td><?= $other_band; ?></td>
</tr>
</table>
<br><br>
<form action="hw_page2.php" method="GET" >
Verify that your profile data shown above is accurate by signing below.
<br>
<input type="text" name="signature" value="" placeholder="Sign Here">
<br>
<input type="checkbox" name="user_certify" value="yes">
I certify, under penalty of purgery, that my profile is accurate.
<br><br>
<button type="button" onclick="window.location='hw_page1.php';"> Go Back: Edit Profile Before Signing </button>
<!-- This is NOT a Submit Button! -->
<br>
<button type="submit"> Record Profile </button>
<!-- This is obviously -->
</form>
</body>
</html>
Please help me figure out where I am making a mistake! I have been working on it for days but I cannot figure out the answer.

PDO MySQL Query only returning one set of results

I built a search form for an app and it is currently only pulling back on result at a time where there should be multiples. I am sure this is something dumb and was wondering if someone can tell me what I am doing wrong.
Here is the full code:
<?php
// php search data in mysql database using PDO
// set data in input text
$TaskId = "";
$ClientId="";
$TaskName = "";
$TaskDescription = "";
$TaskStartAt = "";
if(isset($_POST['Find']))
{
// connect to mysql
try {
$pdoConnect = new PDO("mysql:host=localhost;dbname=tt","root","root");
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
// id to search
//$TaskId = $_POST['TaskId'];
$ClientId = $_POST['ClientId'];
// date to search
//$DateCreated = $_POST['DateCreated'];
// mysql search query
$pdoQuery = "SELECT *
FROM tasks t
left join users u using (UserId)
left join clients cl using (ClientId)
WHERE t.isdeleted = 0 and ClientId = :ClientId";
$pdoResult = $pdoConnect->prepare($pdoQuery);
//set your id to the query id
$pdoExec = $pdoResult->execute(array(":ClientId"=>$ClientId));
if($pdoExec)
{
// if id exist
// show data in inputs
if($pdoResult->rowCount()>0)
{
echo '<table>';
foreach
($pdoResult as $rows)
{
//$TaskId = $row['TaskId'];
$ClientId = $rows['ClientId'];
// $TaskName = $row['TaskName'];
// $TaskDescription = $row['TaskDescription'];
}
echo '</table>';
}
// if the id not exist
// show a message and clear inputs
}else{
echo 'ERROR Data Not Inserted';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Task Tracker</title>
<link rel="stylesheet" href="css/table.css" type="text/css" />
<link rel="stylesheet" href="assets/demo.css">
<link rel="stylesheet" href="assets/header-fixed.css">
<link href='http://fonts.googleapis.com/css?family=Cookie' rel='stylesheet' type='text/css'>
<script type="text/javascript">
//Display the Month Date and Time on login.
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
}
</script>
</head>
<body>
<header class="header-fixed">
<div class="header-limiter">
<h1>Task Tracker</h1>
<nav>
<a href="dashboard.php" class =>Dashboard</a>
<a href="addtask.php" class=>Task Management</a>
<a href="configuration.php" class =>Configuration</a>
<a href="logout.php" class =>Logout</a>
Reports & Analytics
</nav>
</nav>
</div>
</header>
<title> Query a task</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<form action="search.php" method="post">
<!-- Enter a Task Id : <input type="text" name="TaskId" value=""> <br><br> -->
Enter a Client Id : <input type="text" name="ClientId" value="<?php echo $ClientId;?>"><br><br>
<input type="submit" name="Find" value="Find Data">
<br> </br>
<table border="0">
<tr COLSPAN=2 BGCOLOR="lightblue">
<td>Id</td>
<td>Client</td>
<td>Task Name</td>
<td>Task Description</td>
<td>Hours</td>
<td>Date Created</td>
<td>Who Completed Task</td>
</tr>
<?php
{
if($pdoResult->rowCount()>0)
{
echo "<tr>".
"<td>".$rows["TaskId"]."</td>".
"<td>".$rows["ClientName"]."</td>".
"<td>".$rows["TaskName"]."</td>".
"<td>".$rows["TaskDescription"]."</td>".
"<td>".$rows["Hours"]."</td>".
"<td>".$rows["DateCreated"]."</td>".
"<td>".$rows["UserName"]."</td>".
"</tr>";
}
else{
echo 'No data associated with this Id';
}
}
?>
</table>
</form>
</body>
</html>
At a quick glance, it seems to be simply that you’ve split your functionalities up too much.
At the top of the page, you establish your database connection and retrieve the result set. Then you echo a table element, foreach through the PDO Statement object and assign the contents of the current row to the variable $rows. Note: the content of the current row.
Further down on the page, you echo the individual fields, using $rows['field']—but you do this outside your foreach loop. Since $rows gets repopulated everytime the loop loops around, and since you don’t destroy the variable after the loop completes, you end up at the end with a variable that still contains the last row from your result set.
You need to put the place where you actually print the contents of each individual row inside the loop that iterates through your statement object to retrieve the fields. On the other hand, you only want to do this at all if any user input has been entered at all, so the whole thing still needs to be inside the positive branch of the very first condition that checks if $_POST['Find'] is set, like in the version below.
I start out here by assigning a variable $results to be an empty string—that’s the value we’ll output if the user hasn’t sent the form at all. If $_POST['Find'] is not empty, then we search the database, iterate through the result set, create an HTML string in this loop, and store the result in the $results variable. If no rows are returned or the execute() call fails entirely, we throw an exception to be handled by an exception handler (that you will have to define at a central level, for your entire project), passing along a generic error message to be displayed to the user.
Note that I’ve also stripped out a lot of extraneous stuff and comments to make the relevant bits clearer and renamed the $rows variable to $row to make it clear that since it’s populated inside a loop, it contains one row, not all of them.
<?php
// Set the global exception handler—should of course be done
// in a global boilerplate file, rather than for each file
set_exception_handler('your_exception_handler_here');
$results = "";
if(!empty($_POST['Find']))
{
$pdoConnect = new PDO("mysql:host=localhost;dbname=tt","root","root");
$pdoConnect->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$ClientId = $_POST['ClientId'];
$pdoQuery = "SELECT *
FROM tasks t
left join users u using (UserId)
left join clients cl using (ClientId)
WHERE t.isdeleted = 0 and ClientId = :ClientId";
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoExec = $pdoResult->execute(array(":ClientId"=>$ClientId));
if($pdoResult->rowCount()>0)
{
$results = '<table border="0">
<tr COLSPAN=2 BGCOLOR="lightblue">
<td>Id</td>
<td>Client</td>
<td>Task Name</td>
<td>Task Description</td>
<td>Hours</td>
<td>Date Created</td>
<td>Who Completed Task</td>
</tr>';
foreach ($pdoResult as $row)
{
$ClientId = $row['ClientId'];
$results .= "<tr>".
"<td>".$row["TaskId"]."</td>".
"<td>".$row["ClientName"]."</td>".
"<td>".$row["TaskName"]."</td>".
"<td>".$row["TaskDescription"]."</td>".
"<td>".$row["Hours"]."</td>".
"<td>".$row["DateCreated"]."</td>".
"<td>".$row["UserName"]."</td>".
"</tr>";
}
$results .= "</table>";
} else {
$return = '<span class="error_message">No data associated with this Id</span>');
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Task Tracker</title>
</head>
<body>
<title>Query a task</title>
<form action="search.php" method="post">
Enter a Client Id : <input type="text" name="ClientId" value="<?php echo $ClientId;?>"><br><br>
<input type="submit" name="Find" value="Find Data">
</form>
<?php
echo $results;
?>
</body>
</html>

return data from php dropdownlist after submit

hey guys i've passed way more time on this then what i originally wanted to...
so i have this code here, where i have a drop list give me data from a sql database from the selection of 3 radio buttons, that all works fine.
My problem come when i want to submit my form and get info of the data in said droplist. all i want is put the selected radio and the selected item in the single drop list in variables in the submission.php that comes after the post method of the form...
anyway thats what i want to do for now
<?php
require "../Scripts/config.php"; // database connection here
?>
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>test</title>
<SCRIPT language=JavaScript>
function reload()
{
for(var i=0; i < document.form1.type.length; i++){
if(document.form1.type[i].checked)
var val=document.form1.type[i].value
}
self.location='bob.php?type=' + val ;
}
</script>
</head>
<body>
<?Php
$tp=$_GET['type']; // getting the value from query string
if(strlen($tp) > 1){$sql="SELECT * FROM Subcategory where cat_id='$tp'";}
echo $sql;
echo "<form name=form1 id=form1 method=post action=submissions2.php>";
echo "<select name=Subcategory id=Subcategory value=''>Subcategory</option>"; // printing the list box select command
foreach ($dbo->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[cat_id]>$row[Subcategory]</option>";
/* Option values are added by looping through the array */
} echo "</select>";// Closing of list box
echo "<br>";
echo "<br>";
echo "<br>";
echo "
<b>Type</b>
<input type=radio name=type value='1_Cosplay' onclick=\"reload()\";>Cosplay
<input type=radio name=type value='1_Modeling' onclick=\"reload()\";>Modeling
<input type=radio name=type value='1_Zombie' onclick=\"reload()\";>Zombie
<input type=submit value=Submit> </form>";
echo "<br>";
echo "<br>";
echo "<br>";
?>
</body>
</html>
and this is the submissions2.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="../Scripts/jquery-1.8.0.min.js"></script>
</head>
<body>
<?php
function filter($data) {
/*$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);*/
return $data;
return $row;
}
foreach($_POST as $key => $value) {
$mydata[$key] = filter($value);
}
echo $mydata['Subcategory'];
echo "<br>";
?>
</body>
</html>
all i seem to be able to get is the radio button choice.
Here is an all-in-one solution. You need to change some references like what the name/local path of the file path is, but anyway, this contains all the code. I can not test the DB stuff but the ajax works if you have the correct url path in the jQuery portion. Note, this solution references itself, not a new page:
// Display errors for troubleshooting
ini_set('display_errors','1');
error_reporting(E_ALL);
class CategorySelector
{
public function LoadSubCat()
{
// You will be subjected to an injection hack if you don't filter or encode this variable
// You should do PDO with prepared statements
$parent_cat = htmlspecialchars($_GET['parent_cat'], ENT_QUOTES);
$query = $this->Fetch("SELECT id,subcategory_name FROM subcategories WHERE categoryID = '$parent_cat'");
// Uncomment this to see how this returns
// $this->PrintPre($query); ?>
<label for="sub_cat">Sub Category</label>
<select name="sub_cat" id="sub_cat">
<?php
if($query !== 0) {
foreach($query as $row) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['subcategory_name']; ?></option>
<?php
}
} ?>
</select>
<?php
}
public function Form()
{
// Get rows for categories
$results = $this->Fetch("SELECT id,category_name FROM categories");
// Uncomment this to see how this returns
// $this->PrintPre($results); ?>
<form name="form1" id="form1" method="post">
<label for="parent_cat">Parent Category</label>
<select name="parent_cat" id="parent_cat">
<?php
if($results !== 0) {
foreach($results as $row) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['category_name']; ?></option>
<?php }
} ?>
</select>
<!-- This is a container that will load in your next menu -->
<div id="sub_cat_container"></div>
<input type="submit" name="submit" value="submit" />
</form>
<?php
}
public $rowCount;
// This is strictly a returning engine for SQL statements
protected function Fetch($_sql)
{
include_once('config.php');
// You really should do prepared statements (PDO)
// This way of calling sql is depricated
$query = mysql_query($_sql);
// Save the row count
$this->rowCount = mysql_num_rows($query);
// If there are rows return them
if($this->rowCount > 0) {
$_array = array();
// Loop through
while($result = mysql_fetch_array($query)) {
$_array[] = $result;
}
}
// Send back your query results for processing
// If no results, return false/0
return (isset($_array))? $_array:0;
}
protected function PrintPre($_array)
{ ?>
<pre>
<?php print_r($_array); ?>
</pre>
<?php
}
}
// Uncomment this for testing that the AJAX is working.
// print_r($_REQUEST);
// This is probably not the best way to do this all, but for sake
// of trying to get it all to work, this whole thing will ajax to
// itself, but if you can get it to work on this one page, you
// can split it up into two pages.
// Ok, so this creates a new instance of this whole system
$builder = new CategorySelector();
// If this page receives a GET request for $_GET['parent_cat'], just process it.
// That action is to call the sub_cat dropdown menu from this object
if(isset($_REQUEST['parent_cat']) && !empty($_REQUEST['parent_cat'])) {
$builder->LoadSubCat();
}
// If there is no request, display the html page
else {
// You should not have space before the <!doctype>. Some browsers act funky if there is space before
?><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">
// I'm not a javascript person, so this portion is kind of sloppy
$(document).ready(function(){
$('#parent_cat').change(function() {
// Get value
var ElmVal = $('#parent_cat').val();
$.ajax({
// You need to reference this page in the "thispage.php" whatever this page is called
url:"/thispage.php?parent_cat="+ElmVal,
success:function(result) {
$("#sub_cat_container").html(result);
}});
});
});
</script>
</head>
<body>
<?php
// Display the form.
$builder->Form(); ?>
</body>
</html>
<?php } ?>
Quote all your HTML attributes like name='Subcategory', and
echo "<option value=$row[cat_id]>$row[Subcategory]</option>"
should be
echo "<option value='{$row['cat_id']}'>{$row['Subcategory']}</option>";
Your coding practice is horrible, by the way. You are not testing to see how many rows you have in your MySQL query, and you don't need to echo on each line. You can do this:
echo '<br />'.
'<br />';
Of course, using line breaks like that is a bad practice, as well. Use CSS.

JQUERY submit form and display result - multiple forms on page

Im new to Jquery and trying to recreate something muddled together a while ago, with a similar function.
i have pasted my code here: http://pastebin.com/SYM45WPw
I have a table which is created base on results of a form on the previous page (this is all working ok) with Student names in the first column, then every column after that has will be a result for testing requirement, simply a drop down with Pass / Fail, and for each person and each requirement i want to go along and pick the result, and submit the results to DB in thhe back ground and then removed the Select option and displays the result.
Currently on the post_result.php i have this, just to text i am getting a result:
if($_POST['studentID'] != ""){
echo "Success";
}
All help is much appreciated,
Edit: (taken from pastebin link)
<?php
ini_set('error_reporting', E_ALL);
$student_name = $_POST['student_name'];
$class = $_POST['class'];
$month = $_POST['month'];
?>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select#result").change(function() {
var studentID = $(this).find("input[name='student_name']").val();
var result = $(this).serialize();
$.post('post_result.php', result, function(data) {
// We not pop the output inside the #output DIV.
$("#output-" + studentID).html(data);
});
$("#"+studentID+"-formarea").hide();
return false;
});
});
</script>
</head>
<body>
<?php
require 'db_connect.php';
$header=1;
$query = mysql_query("SELECT * FROM requirements WHERE `class` = '$class' && month = $month ") or die("Error:". mysql_errno());
?>
<table class="tg" border="1">
<tr>
<th class="tg-031e">Student Name</th>
<?php while ($row = mysql_fetch_array($query)) {
echo '<th class="tg-031e">'.$row['requirement'].'</th>';
$header++;
}
?>
</tr>
<?php
for ($i = 0; $i < count($student_name); $i++) {
echo '<tr>';
echo ' <td class="tg-031e">'.$student_name[$i].'</td>';
for ($count = 1; $count < $header; $count++) {
echo '<td><div id="'.$student_name.'-formarea">'
. '<form method="POST" id="form-'.$student_name.'">'
. '<input type="hidden" name="student_name" value="'.$student_name.'" />'
. '<select name="result" id="result"><option selected>Select Result</option>'
. '<option value="Pass">Pass</option><option value="Fail">Fail</option></select>'
. '</form></div>'
. '<div id="output-'.$student_name[$i].'"></div></td>';
}
echo'</tr>';
}
?>
</table>
</body>
</html>
You're serializing a Select element, not the form, and you must serialize the form.
For example:
<form id="myForm" action="blabla" method="blabla">
<select id="result" name="result">
<option>Bla Bla Bla</option>
</select>
<input type="text" name="student_name" />
<!-- ...more elements .... -->
</form>
So you have to replace:
var result = $(this).serialize()
//by:
var result = $("#myForm").serialize()
In the file you are sending data to via Ajax you have 'studentID' as your key but in the form you are serializing, the keys are assigned from the name='' attribute. That would make your keys: 'student_name' and 'result'.
if($_POST['studentID'] != ""){
echo "Success";
}
One way you could make sure of this is by placing the following into the php file your Ajax is sending and receiving. This will print an array of the post content being received by your php file.
print_r($_POST);
The results form that array will show up in the div where you are telling Ajax to place the results.
This is a good way to serialize the form you are working on for Ajax.
var result = $(this).closest('form').serialize();

Drop Down populated by mysql selection not posting

I'm new to PHP here and struggling with an issue. I've created a form to submit information to a powershell script on the back end. I have one drop down field (telephone) that is pulling from mysql and populating. That part is working great. The issue that I am having is that when i go to post the data and pass it to the powershell script that field (telephone) is being passed as blank. I'm not sure where I may have caused the issue and looking for some help here.
Here is what I have. I'd like to keep it in PHP if possible.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<?php
// If there was no submit variable passed to the script (i.e. user has visited the page without clicking submit), display the form:
if(!isset($_POST["submit"]))
{
?>
<form name="testForm" id="testForm" action="BTAM2.php" method="post" /> <br />
First Name: <input type="text" name="SAMname" id="SAMname" maxlength="20" /><br /> <br/>
Telephone Number:
<?php
$con=mysqli_connect("localhost","root","","it");
//============== check connection
if(mysqli_errno($con))
{
echo "Can't Connect to mySQL:".mysqli_connect_error();
}
//This creates the drop down box
echo "<select name='phonenum' id='phonenum'>";
echo '<option value="0">'.' '.'</option>';
$query = mysqli_query($con,"Select `btphonenumber` from `btphone` where `btuser` = ' '");
$query_display = mysqli_query($con,"SELECT * FROM btphone");
while($row=mysqli_fetch_array($query))
{
echo "<option value='". $row['id']."'>".$row['btphonenumber']
.'';
}
echo '</select>';
?><br /> <br />
<input type="submit" name="submit" id="submit" value="Create User" />
</form>
<?php
}
// Else if submit was pressed, check if all of the required variables have a value:
elseif((isset($_POST["submit"])) && (!empty($_POST["SAMname"])))
{
// Get the variables submitted by POST in order to pass them to the PowerShell script:
$firstname = $_POST["SAMname"];
$telenumber = $_POST["phonenum"];
var_dump($_REQUEST);
}
// Else the user hit submit without all required fields being filled out:
else
{
echo "Sorry, you did not complete all required fields. Please go back and try again.";
}
?>
I've resolved my own issue. in the line
echo "<option value='". $row['id']."'>".$row['btphonenumber']
I should have had
echo "<option value='". $row['btphonenumber']."'>".$row['btphonenumber']

Categories