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.
Related
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.
i have few field of data such as product , amount and barcode.The system just show 1 row of data insert form that contain the 3 field.when i completed insert the first row, then second row of textbox will auto generate, i can do it by microsoft access, can i do so for php ?
<?php $i=0; ?>
<form method="post" action="">
<input type="text" name="<?php echo $i; ?>" />
</form>
<?php
if(isset($_POST[$i])){
$i++;
?>
<form method="post" action="">
<input type="text" name="<?php echo $i; ?>" />
</form>
<?php }?>
it work for the first and second textbox, but how can i continue to create more textbox accordingly?
say your file name is 1.php and you will submit the form to 1a.php
1.php
<html>
<head>
<script>
a=0;
function generate()
{
if(document.getElementById(a).value!="")
{
var new_input=document.getElementById(a).cloneNode(true);
//document.getElementById(a).type="hidden";//uncomment this statement to hide the previous input box.
new_input.id=++a;
new_input.title='product_no:'+(a+1);
new_input.value="";
document.getElementById('input_section').appendChild(new_input);
}
else
{
alert("Give some value first.");
document.getElementById(a).focus();
}
}
</script>
</head>
<body>
<form method="post" action="1a.php">
<span id="input_section">
<input type="text" onFocus="this.name='prod[]'; this.id=a; this.title='product_no:'+(a+1);"/>
</span>
<input type="button" value="Insert&Generate" onClick="try{generate()} catch(e){alert(e)}">
<input type="submit" value="INSERT ALL">
</form>
</body>
</html>
1a.php
<html>
<?php
if(count($_POST)==0)
{
?>
<script>
alert('No record to insert.')
location.href="1.php";
</script>
<?php
}
$con=mysqli_connect(...);// connect to database
foreach($_POST['prod'] as $prod_info)
{
$prod_info_arr=explode(",",$prod_info);
$sql="insert into tab1(product, amount, barcode) values('".$prod_info_arr[0]."', ".$prod_info_arr[1].", '".$prod_info_arr[2]."')";
mysqli_query($sql);
}
?>
</html>
This is what you wanted. Check it.
edit: just added comment on the statement document.getElementById(a).type="hidden"; to make the filled textbox not disappear.
If you want to have dynamic input fields, so that second and third input boxes are displayed only when the first input box is filled, use an AJAX code.
This must be what you want. Since you have not mentioned clearly under what condition the second input field should be displayed, i assumed if 'try' is inserted in the first input field, second input field is shown.
<?php
echo "<script>
function showUser(str)
{
if (str=='')
{
document.getElementById('txtHint').innerHTML='';
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('txtHint').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','get.php?q='+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form method='post' action=''>
First input<input type='text' name='name' onclick='showUser(this.value)' /></br>
<div id='txtHint'></div>
</form>
</body>
</html>";
?>
And in get.php file the following code;
<?php
$q = $_GET['q'];
if($q == 'try'){
echo "Second input<input type='text' />";
}
?>
Hope this will help. And change the get.php code according to the condition you want the second input field to be shown.
This code works. After entering try in the first input field again click inside the text field. And then second input field will be shown.
I've done this so often before on different websites, but can't get it to work now.
I've got a simple form that posts perfectly well using a submit button, but for a specific reason I actually need it to submit via a url link instead. I'm using submit(). The form submits, but the data isn't posting.
What am I missing?
<html>
<body>
<?
if(isset($_POST['bar'])) { echo 'testing button<br>'; }
if(isset($_POST['information'])) {
echo $_POST['information'];
echo '</br>Info successfully posted.';
}
?>
<form action="test.php" method="post" id="fooform">
Hello World.<br>
Select checkbox: <input type="checkbox" id="information" name="information" value="yes">
<input type="submit" name="bar" value="Send"><br>
Confirm and Post<br>
Post Directly
</form>
<script type="text/javascript">
function SubmitForm(formId) {
var oForm = document.getElementById(formId);
alert("Submitting");
if (oForm) { oForm.submit(); }
else { alert("DEBUG - could not find element " + formId); }
}
</script>
</body>
</html>
The form starts to submit, then the href of the link is followed, and this cancels the form submission.
If you are using old-style onclick attributes, then return false; at the end to prevent the default action.
You would, however, be better off using a submit button (you are submitting a form). You can use CSS to change its appearance.
Try this code :
<html>
<body>
<?php
if (isset($_POST['bar'])) {
echo 'testing button<br>';
}
if (isset($_POST['information'])) {
echo $_POST['information'];
echo '</br>Info successfully posted.';
}
?>
<form action="test.php" method="post" id="fooform">
Hello World.<br>
Select checkbox: <input type="checkbox" id="information" name="information" value="yes">
<input type="submit" name="bar" value="Send"><br>
Confirm and Post<br>
Post Directly
</form>
<script type="text/javascript">
function SubmitForm(formId) {
var oForm = document.getElementById(formId);
alert("Submitting");
if (oForm) {
oForm.submit();
}
else {
alert("DEBUG - could not find element " + formId);
}
}
</script>
</body>
</html>
try to submit form with form id in jquery
<a class="submit">Post Directly </a>
$('a.submit').click(function(){
$('#fooform').submit();
})
I want to write a php page in which there is a html form. I want to send all input (number for example) of my form to a php function (instead of a javascript function; I make this to hide my javascript function code).
How can I send input value to php function?
Is it possible to call the php function through onclick="function(param1, param2)"?
I know that javascript is a client-side language while php is server-side.
If it is possible, how can I write the return of the function in an input field?
I want to remain in my page.
Is it correct - action="#"?
My code is:
<form action="#" method="get">
Inserisci number1:
<input type="text" name="val1" id="val1"></input>
<?php echo "ciaoooo"; ?>
<br></br>
Inserisci number2:
<input type="text" name="val2" id="val2"></input>
<br></br>
<input type="submit" value="send"></input>
</form>
Help me in the implementation of the simple php function and in the passage of values from input to function!
Thanks!
Make your action empty. You don't need to set the onclick attribute, that's only javascript. When you click your submit button, it will reload your page with input from the form. So write your PHP code at the top of the form.
<?php
if( isset($_GET['submit']) )
{
//be sure to validate and clean your variables
$val1 = htmlentities($_GET['val1']);
$val2 = htmlentities($_GET['val2']);
//then you can use them in a PHP function.
$result = myFunction($val1, $val2);
}
?>
<?php if( isset($result) ) echo $result; //print the result above the form ?>
<form action="" method="get">
Inserisci number1:
<input type="text" name="val1" id="val1"></input>
<?php echo "ciaoooo"; ?>
<br></br>
Inserisci number2:
<input type="text" name="val2" id="val2"></input>
<br></br>
<input type="submit" name="submit" value="send"></input>
</form>
You need to look into Ajax; Start here this is the best way to stay on the current page and be able to send inputs to php.
<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
This gets the users input on the textbox and opens the webpage gethint.php?q=ja from here the php script can do anything with $_GET['q'] and echo back to the page James, Jason....etc
This is pretty basic, just put in the php file you want to use for processing in the element.
For example
<form action="process.php" method="post">
Then in process.php you would get the form values using $_POST['name of the variable]
No, the action should be the name of php file. With on click you may only call JavaScript. And please be aware the hiding your code from the user undermines trust. JS runs on the browser so some trust is needed.
You can write your php file to the action attr of form element.
At the php side you can get the form value by $_POST['element_name'].
you must have read about function call . here i give you example of it.
<?php
funtion pr($n)
{
echo $n;
}
?>
<form action="<?php $f=$_POST['input'];pr($f);?>" method="POST">
<input name=input type=text></input>
</form>
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