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();
Related
Hi I'm trying to match a user id value from an input on a form to records in my database. I'm trying to show a column (itemname) of data in a dropdown select menu that match a userid value from a forms input. I don't know if I'm properly defining my variables or what im doing wrong but cant see what I'm missing. Any help is greatly appreciated. Thanks.
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
// Check if the connection failed
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
if (isset($_POST['userid']))
{
$userid= $_POST['userid'];
$query = "SELECT itemname
FROM seguin_orders
WHERE username = '".($userid)."'";
$result = mysqli_query($con,$query);
}
?>
FORM WITH DROPDOWN
<form action="xxx" method="post" name="form1">
<select name="xxx"><option value="">-- Select One --</option>
<?php
while ($row = mysqli_fetch_assoc($result))
{
echo '<option value =" ' . $row['itemname'] . ' ">' . $row['itemname'] . '</option>';
}
?>
</select>
<input id="input1" name="input1" type="text" />
</br>
<input id="userid" name="userid" type="text" value="demo#gmail.com" readonly="readonly"/>
<button type="submit" value="Submit">Submit</button>
</form>
==SOLUTION FOR AJAX FORM==
orders.php
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
// Check if the connection failed
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
if (isset($_GET['userid']))
{
$userid= $_GET['userid'];
$query = "SELECT itemname
FROM seguin_orders
WHERE username = '".($userid)."'";
$result = mysqli_query($con,$query);
while ($row = mysqli_fetch_assoc($result))
{
echo '<option value =" ' . $row['itemname'] . ' ">' . $row['itemname'] . '</option>';
}
}
?>
original page with form
This is just basic and simple, for you to understand. You can change it and make more secure. Please, read comments to understand
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="#">
<div class="pre-dropdown"> <!-- This class is here to hide this mini form after submit with jquery -->
<input type="text" name="userid" id="userid">
<button id="submitId">Submit Id</button>
</div>
<div class="dropdown"> <!-- This is hidden because there is no data, but when userid is submited, this will be visible -->
<select name="xxx" id="dropdown-select">
<option value="">-- Select One --</option>
</select>
</div>
</form>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(function(){
$('.dropdown').hide(); // Hide dropdown div when page is loaded, mbetter way will be with css, but it's enough for now
$('#submitId').on('click', function(e){ // Things to do when 'Submit Id' button is clicked
var userid = $('#userid').val(); // Grab user id from text field
e.preventDefault(); // Prevent form from submit, we are submiting form down with ajax.
$.ajax({
url: "orders.php",
data: {
userid: userid
}
}).done(function(data) {
$('.pre-dropdown').hide(); // Hide mini form for user id
$('.dropdown').show(); // show dropdown
$('#dropdown-select').append(data); // append results from orders.php to select
});
});
});
</script>
</body>
</html>
Change form the way you need. I am hidding pre-dropdown because if user submits userid again, we will append results twice.
You did two mistakes
You miss end of if condition ending }, and remove semicolon ; from while loop also string ending is missing.
In short you need a good IDE that can let tell you basic error in your code
Try Changing echo of your code to something like this-->
echo "<option value =\"". $row['itemname'] ."\">". $row['itemname'] . "</option>";
or try using mysqli_fetch_array() rather than mysqli_fetch_assoc()
And More Over change your sql query to something like this
$query = "SELECT itemname FROM seguin_orders WHERE username = '$userid'";
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.
I am trying to fill a listbox on a webpage and I want the listbox to start blank. Once the button is clicked the listbox should populate. My code below automatically fills the listbox but I would rather have the button do it.
<?php
$dbc = mysql_connect('','','')
or die('Error connecting to MySQL server.');
mysql_select_db('MyDB');
$result = mysql_query("select * from tblRestaurants order by RestName ASC");
?>
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SEARCH</title>
</head>
<body>
<form method="post" action="1004mcout.php">
<p><center>SEARCH</CENTER></P>
<select name="RestName">
<?php
while ($nt= mysql_fetch_assoc($result))
{
echo '<option value="' . $nt['RestID'] . '">' . $nt['RestName'] . '</option>';
}
?>
</select>
<p> SPACE</p>
<p>Click "SUBMIT" to display the calculation results</p>
<input type="submit" name="Submit" value="Submit" />
<br />
</form>
</body>
</html>
I would either: Preload the data into the page as some ready but invisible html list (maybe a bit n00b), or save the data as a javascript array and a function will load it into the page (better), or do an ajax call to the same page (for simplicity) (probably best, leaves you the option open for updated data after page initiation).
The Ajax route will have to use jQuery (change this_page.php to whichever page this is called):
<?php
while ($nt= mysql_fetch_assoc($result))
$arrData[] = $nt;
//If you want to test without DB, uncomment this, and comment previous
/*$arrData = array(
array('RestID' => "1", 'RestName' => "Mike"),
array('RestID' => "2", 'RestName' => "Sebastian"),
array('RestID' => "3", 'RestName' => "Shitter")
);*/
if(isset($_GET["ajax"]))
{
echo json_encode($arrData);
die();
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function displayItems()
{
$.getJSON("this_page.php?ajax=true", function(data) {
$.each(data, function(index, objRecord) {
var option=document.createElement("option");
option.value=objRecord.RestID;
option.text=objRecord.RestName;
$("#RestName").append('<option value="' + objRecord.RestID + '">' + objRecord.RestName + '</option>');
});
});
}
</script>
<title>SEARCH</title>
</head>
<body>
<form method="post" action="1004mcout.php">
<p><center>SEARCH</CENTER></P>
<select id="RestName"></select>
<p> SPACE</p>
<p>Click "SUBMIT" to display the calculation results</p>
<button type="button" onclick="javascript:displayItems();">Insert options</button>
<br />
</form>
</body>
</html>
Essentially, what it does, it collects the data, checks if there is a request for the ajax data in the url, if not, it prints the rest of the page (with an empty select). If there is an ajax flag in the url, then the php will encode the data into json, print that and stop.
When the User receives the page with an empty select, it clicks the button which will trigger the displayItems() function. Inside that function, it does a jQuery-based ajax call to the same page with the ajax flag set in the url, and the result (which is json), is evaluated to a valid javascript array. That array is then created into options and loaded into the RestName SELECT element.
A final cookie? You could just print the data as options, into the select anyway, just like the previous answers described. Then, inside the displayItems() function, you clear the select before loading it from the jQuery/ajax call. That way, the user will see data right from the beginning, and will only update this with the most recent data from the DB. Clean and all in one page.
<?php
$dbc = mysql_connect('','','')
or die('Error connecting to MySQL server.');
mysql_select_db('MyDB');
$result = mysql_query("select * from tblRestaurants order by RestName ASC");
?>
<html>
<head>
<script>
function displayResult()
{
var x =document.getElementById("RestName");
var option;
<?php
while ($nt= mysql_fetch_assoc($result))
{
echo 'option=document.createElement("option");' .
'option.value=' . $nt['RestID'] . ';' .
'option.text=' . $nt['RestName'] . ';' .
'x.add(option,null);';
}
?>
}
</script>
</head>
<body>
<select name="RestName">
</select>
<button type="button" onclick="displayResult()">Insert options</button>
</body>
</html>
Read more about adding options to select element from java script here
how about this simple way,
is this what you mean,
its not safe, any one can post show=yes but i think you just like users to be able to simply click and see result
<select name="RestName">
<?php
// if show=yes
if ($_POST['show'] == "yes"){
$dbc = mysql_connect('','','')
or die('Error connecting to MySQL server.');
mysql_select_db('MyDB');
$result = mysql_query("select * from tblRestaurants order by RestName ASC");
while ($nt= mysql_fetch_assoc($result))
{
echo '<option value="' . $nt['RestID'] . '">' . $nt['RestName'] . '</option>';
}
}
?>
</select>
<form method="post" action="#">
<input type="hidden" name="show" value="yes" />
<input type="submit" name="Submit" value="Submit" />
</form>
you can also simply use a hidden div to hid listbox and give the button an onclick action to show div, learn how in here: https://stackoverflow.com/a/10859950/1549838
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.
I'm trying to learn HTML and PHP. In an example which i found over the internet i need to set a variable to the submit button. So when the submit button is pressed, this page reloads, with a variable in the address bar,the variable is the one from the drop down menu. like this :
test.php?idneeded=$variable
in which the $variable is selected by the user and then the page reloads to show specific content related to the chosen option.
For example :
test.php?idneeded=40
(40 is "MadTechie" from the drop down form)
the code i found is this :
<?php
if( isset($_GET['ajax']) )
{
//In this if statement
switch($_GET['ID'])
{
case "LBox2":
$Data[1] = array(10=>"-Tom", 20=>"Jimmy");
$Data[2] = array(30=>"Bob", 40=>"-MadTechie");
$Data[3] = array(50=>"-One", 60=>"Two");
break;
//Only added values for -Tom, -MadTechie and -One (10,40,50)
case "LBox3":
$Data[10] = array(100=>"One 00", 200=>"Two 00");
$Data[40] = array(300=>"Three 00");
$Data[50] = array(1000=>"10000");
break;
}
echo "<option value=''></option>";
foreach($Data[$_GET['ajax']] as $K => $V)
{
echo "<option value='$K'>$V</option>\n";
}
mysql_close($dbh);
exit; //we're finished so exit..
}
$Data = array(1=>"One", 2=>"Two", 3=>"Three");
$List1 = "<option value=''></option>";
foreach($Data as $K => $V)
{
$List1 .= "<option value='$K'>$V</option>\n";
}
?>
<!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" />
<title>Simple Dymanic Drop Down</title>
<script language="javascript">
function ajaxFunction(ID, Param)
{
//link to the PHP file your getting the data from
//var loaderphp = "register.php";
//i have link to this file
var loaderphp = "<?php echo $_SERVER['PHP_SELF'] ?>";
//we don't need to change anymore of this script
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch(e){
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
//the line below reset the third list box incase list 1 is changed
document.getElementById('LBox3').innerHTML = "<option value=''></option>";
//THIS SET THE DAT FROM THE PHP TO THE HTML
document.getElementById(ID).innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", loaderphp+"?ID="+ID+"&ajax="+Param,true);
xmlHttp.send(null);
}
</script>
</head>
<body>
<!-- OK a basic form-->
<form method="post" enctype="multipart/form-data" name="myForm" target="_self">
<table border="0">
<tr>
<td>
<!--
OK here we call the ajaxFuntion LBox2 refers to where the returned date will go
and the this.value will be the value of the select option
-->
<select name="list1" id="LBox1" onchange="ajaxFunction('LBox2', this.value);">
<?php
echo $List1;
?>
</select>
</td>
<td>
<select name="list2" id="LBox2" onchange="ajaxFunction('LBox3', this.value);">
<option value=''></option>
<!-- OK the ID of this list box is LBox2 as refered to above -->
</select>
</td>
<td>
<select name="list3" id="LBox3">
<option value=''></option>
<!-- OK the ID of this list box is LBox3 Same as above -->
</select>
</td>
</tr>
</table>
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
I haven't started learning JavaScript, and i need this for a project. I'll appreciate it if anyone can help me on this.
Thanks.
i don't understand your question vary well but i'll try to help you in general. in the html be sure that you use the method="get" for the form and in this way the variables are passed to the php in the url. (in other cases POST needed but for now you are ok even with get). all the input's values with the NAME attribute set are passed into the url. ex:
<form action='phpscript.php' method='get' >
<input type='text' name='just_a_test' value='somevalue' />
<input type='submit' value='submit_form' name='submit' />
</form>
the url after submiting will be :
http://mypage.com/phpscript.php?just_a_test=somevalue&submit=submit_form
in the other side the php script that will use the data from the form will be
<?php
if (isset($_GET['submit']) ) {
if (isset($_GET['just_a_test']) )
{
$variable1 = $_GET['just_a_test'];
//do something with variable 1 and output results
//based on the value of this variable.
}
}
?>
you can do the same thing for ass many variables as you want . i hope this was a help to you because i cant undestand your question better than this .
If the form is supposed to be sent during a redirect, you are not using AJAX. In this case the solution is simple:
<form name="myForm" action="test.php" method="GET">
<select name="idneeded">
<option value="40">MadTechie</option>
<option>...</option>
</select>
</form>
Things like these are explained in every HTML tutorial. This is a good starting point: W3C Schools.
You haven't mentioned if the value of the variable is available on client or server?
Variable on Client:
Basically, you will have to handle the onSubmit event of the form. Here you can append the value of the variable to the action.
Variable on Server:
Here you would change the action when you are rendering the HTML.