How to update data when input is drop down? - php

I am so new in html, php, javascript, mysql. i created a drop down menu using java script that contains a list of 2011 to 2510. During update i can not display the stored value that is generated using java script. I searched but found nothing. A portion of code.....
<select name="eca">
<option id="eca" required="required" class="ecadetail" value="NSS" <?php if ($eca == 'NSS') echo 'selected="selected"';?>">NSS</option>
<option id="eca" required="required" class="ecadetail" value="NCC" <?php if ($eca == 'NCC') echo 'selected="selected"';?>">NCC</option>
<option id="eca" required="required" class="ecadetail" value="Cultural" <?php if ($eca == 'Cultural') echo 'selected="selected"';?>">Cultural</option>
</select>
</div>
<div class="label">Year</div>
<div class="inputyear">
<select name="years" >
<script language="JavaScript">
// loop to create the list
var year = 2010
for (var i=1; i <=500; i++)
{
year++;
document.write("<option>" + year + "</option>");
}
// end JS code hide -->
<option value="<?php if ($year == 'year') echo 'selected="selected"';?>"></script>
</script>
</select>
</div>
</div> <!-- end of 7th row -->
the value for eca is working fine. The value year is stored in $year.
help please...

This loop can purely done in php then why involving the javascript
<select name="years" >
<?php
$matchyear = 2010;
for ($i=2010; $i <=2510; $i++)
{ ?>
<option value="<?php echo $i;?>" <?php if ($i== $matchyear) echo 'selected="selected"';?>><?php echo $i;?> </option>
<?php }
?>
</select>
Make things easier for you not a complex programming so that other person can understand easily and call you by good names

Related

Make certain criteria appear when selection is made?

User have some options, upon selecting one of them, I want to show more options which will depend on first selected option. Say, user has options to select the number of gates, like 1 or 2. Upon selecting a number I want to show options of all the gates lower than that number. That is,
if 1 is selected, show options of only gate 1.
if 2 is selected, show options of gate 2 and gate 1.
I have most of the variables within my phpmyadmin for storage purposes to avoid having to create alot of variables in the code. Just want some suggestions and if you see anything I can improve let me know.
<div class="form-div-element">
<label># of Gates</label>
<select class="gates-change" name="no_gate" required>
<option value="">Select Gate</option>
<option value="28">1 Gate</option>
<option value="29">2 Gates</option>
</select>
</div>
<?php
if($result)
{
foreach($result as $row)
{
if($row->id == 31 || $row->id == 32 || $row->id == 33)
{?>
<div class="form-div-element ecl-variation ecl-variation<?php echo $row->id;?>" style="display:block!important">
<?php }
else
{?>
<div class="form-div-element ecl-variation ecl-variation<?php echo $row->id;?>">
<?php }?>
<label><?php echo $row->variation_name;?></label>
<?php
if($row->variation_name == 'Stops')
{?>
<input type="hidden" name="stopvariationid" value="<?php echo $row->id;?>" id="stopvariationid"/>
<?php }
?>
<?php
$var_value = (explode("|",$row->variation_value));
$var_condition = $row->conditions;
$arr = array('height_convert_configuration');
//if($row->special_features != '')
//{
// check_special_function($var_value,$row->special_features,$var_condition);
//}
//else if($row->variation_type =='selectbox')
if($row->variation_type =='selectbox')
{
if($row->variation_function == 'calculation')
{?>
<select onchange = 'change_variation(this.value,<?php echo $row->id;?>)'>
<option value="">Select Option</option>
<?php for($i=0;$i<count($var_value);$i++)
{?>
<option value="<?php echo $var_value[$i];?>"><?php echo $var_value[$i];?></option>
<?php }?>
</select>
<?php }
else
{ ?>
<select class="gate_datatype" name="gate_type">
<option value="">Select Option</option>
<?php for($i=0;$i<count($var_value);$i++)
{?>
<option value="<?php echo $var_value[$i];?>|<?php echo $row->special_features;?>"><?php echo $var_value[$i];?></option>
<?php }?>
</select>
<?php }
}
else if($row->variation_type =='textbox')
{?>
<?php for($i=0;$i<count($var_value);$i++)
{?>
<?php echo $var_value[$i];?>
<?php }?>
<?php }
else if($row->variation_type =='radiobox')
{?>
<?php for($i=0;$i<count($var_value);$i++)
{?>
<div class="radiobox-cont">
<input onchange = 'change_radio_variation(this,this.value,<?php echo $row->id;?>)' type="radio" name="<?php echo $row->class;?>" value='<?php echo $var_value[$i];?>' /><?php echo $var_value[$i];?>
</div>
<?php }?>
<?php }
else if($row->variation_type =='checkbox')
{?>
<?php for($i=0;$i<count($var_value);$i++)
{?>
<div class="checkbox-cont <?php echo preg_replace('/\s+/', '_', $var_value1[$i]);?>">
<?php if('Cabin Telephone' == $var_value[$i])
{?>
<input checked type="checkbox" onchange="change_check_varitaion(this,this.value,<?php echo $row->id;?>)" name="other_option[]" value='<?php echo $var_value[$i];?>' disabled="disabled" /><?php echo $var_value[$i];?>
<?php }
else
{?>
<input type="checkbox" onchange="change_check_varitaion(this,this.value,<?php echo $row->id;?>)" name="other_option[]" value='<?php echo $var_value[$i];?>' /><?php echo $var_value[$i];?>
<?php }?>
</div>
<?php }?>
<?php }?>
</div>
<?php }
You can do this in two ways first way is to do ajax and second way is using css.
First method suppose this is your select code where you can select gate
<div class="form-div-element">
<label># of Gates</label>
<select id="gates" onchange="change()" class="gates-change" name="no_gate" required>
<option value="">Select Gate</option>
<option value="28">1 Gate</option>
<option value="29">2 Gates</option>
</select>
</div>
// and this is your sub gates options which will be empty at first and its display will be none
<div id="subgates_div" class="form-div-element" style="display:none;">
<label># of Sub Gates</label>
<select id="subgates" class="gates-change" name="sub_no_gate" required>
<option value="">Select Sub Gate</option>
</select>
</div>
on selecting gate what you can do is use ajax to get the sub options of the selected gate like this. in this code your url and my url will be different.
function change() {
var selected = $('#gates').find(":selected").attr("value");
$.ajax({
type: "POST",
url: '<?php echo base_url('get_sub_options') ?>',
dataType: 'json',
data: {category: selected},
success: function (data) {
console.log(data);
//remove disabled from province and change the options
$('#subgates_div').show();
$('select[name="sub_no_gate"]').html(data.subgates);
}
});
}
and your php function should be like this here first i have made an array named subgates. and i have retrieved subgates from database using the value from post. this query might be different in your case. the i have applied foreach loop for sub gates and created a new option element with respective subgate id and subgate name and appended it to array. and at last the array is returned using json_encode
function get_sub_category() {
$data['subgates'] = array();
$subgates = $this->db->get_where('subcategories', array('id' => $_POST['category']))->result();
foreach ($subgates as $key => $val) {
$data['subgates'][] = <<<EOD
<option value='$val->id'>$val->sub_gate_name</option>
EOD;
}
echo json_encode($data);
}
and the other method is using css. to do this you should list all this options of gate and subgates at first. like this
// gates options
<div class="form-div-element">
<label># of Gates</label>
<select id="gates" onchange="change()" class="gates-change" name="no_gate" required>
<option value="">Select Gate</option>
<option value="28">1 Gate</option>
<option value="29">2 Gates</option>
</select>
</div>
//sub gate options one
<div id="subgates-<?php echo $subgates->id; ?>" class="form-div-element" style="display:none;">
<label># of Sub Gates</label>
<select id="subgates" class="gates-change" name="sub_no_gate" required>
<option value="">Select Sub Gate</option>
</select>
</div>
//sub gate option 2
<div id="subgates-<?php echo $subgates->id; ?>" class="form-div-element" style="display:none;">
<label># of Sub Gates</label>
<select id="subgates" class="gates-change" name="sub_no_gate" required>
<option value="">Select Sub Gate</option>
</select>
</div>
// and so on
In this case what you should remember is that your sub gates option div id should be dynamic and display will be none at first
now when you select a gate use onchange and change the display css of respective sub gates like this
function change() {
$(".form-div-element").hide();
var selected = $('#gates').find(":selected").attr("value");
$('#subgates-'+selected).show();
}
hope this will give you some idea and if you have any confusion feel free to ask
All in all it seems to me that your question actually contains 2 questions:
How to dynamically show/hide DOM elements based on user selection
Upon selecting a number I want to show options of all the gates lower than that number.
How to optimize your PHP code
Just want some suggestions and if you see anything I can improve let me know.
Number two is way to broad! Maybe just one quick suggestion: If it works then its fine. Overlooked it fast and seems to be ok.
See my working snippet for number one, which actually only needs a little customization of your existing source code (if any at all). Don't forget its just a mockup; if you need some further help or want some deeper explanations about whats going on then let me know...
jQuery('.form-div-element').not('.ecl-variation').find('select').on('change', function() {
var i = -1,
$conditional = jQuery('.ecl-variation').hide(), // hide in advance
iGates = +(jQuery(this).find('option:selected').attr('data-gates-sum')); // get required gate(s) based on selected options "data-gates-sum"-attribute
// version based on text: `iGates = +($(this).find('option:selected').text().split(' ')[0])` | pro: no additional markup, con: error prone, maintenance
// count up to required gate(s) and make them visible
while ( ++i < iGates ) {
$conditional[i].style.display = 'block';
}
});
.ecl-variation{
display: none; /* hide conditional selects in advance */
}
<!-- minimized mockup -->
<div class="form-div-element">
<label># of Gates</label>
<select>
<option value="">Select Gate</option>
<!-- decided to add a data attribute instead of relying on text which could change more likely (maintenance) -->
<option value="28" data-gates-sum="1">1 Gate</option>
<option value="29" data-gates-sum="2">2 Gates</option>
</select>
</div>
<div class="form-div-element ecl-variation">
<label># of Gates | conditial 1</label>
<select>
<option value="">Select Gate Sub</option>
<option value="3">abc</option>
<option value="4">xyz</option>
</select>
</div>
<div class="form-div-element ecl-variation">
<label># of Gates | conditial 2</label>
<select>
<option value="">Select Gate Sub</option>
<option value="5">123</option>
<option value="6">789</option>
</select>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How to implement?
.ecl-variation{
display: none; /* hide conditional selects in advance */
}
<body>
<!-- minimized mockup -->
<div class="form-div-element">
<label># of Gates</label>
<select>
<option value="">Select Gate</option>
<option value="28" data-gates-sum="1">1 Gate</option>
<option value="29" data-gates-sum="2">2 Gates</option>
</select>
</div>
<div class="form-div-element ecl-variation">
<label># of Gates | conditial 1</label>
<select>
<option value="">Select Gate Sub</option>
<option value="3">abc</option>
<option value="4">xyz</option>
</select>
</div>
<div class="form-div-element ecl-variation">
<label># of Gates | conditial 2</label>
<select>
<option value="">Select Gate Sub</option>
<option value="5">123</option>
<option value="6">789</option>
</select>
</div>
<!-- YOUR CODE ENDS HERE -->
<!-- load jquery from cdn -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<!-- provide a local copy as fallback in case that cdn is not available -->
<script>window.jQuery||document.write('<script src="path/to/your/local/copy/jquery-1.12.4.min.js"><\/script>')</script>
<!-- implement your custom site specific script(s) inline -->
<script>
(function( $ ) {
$('.form-div-element').not('.ecl-variation').find('select').on('change', function() {
var i = -1,
$conditional = $('.ecl-variation').hide(),
iGates = +($(this).find('option:selected').attr('data-gates-sum'));
while ( ++i < iGates ) {
$conditional[i].style.display = 'block';
}
});
})( jQuery )
</script>
<!-- instead of deploying your scripts inline you can load them also like this:
<script src="path/to/your/app.js"></script>
-->
</body><!-- make sure that your scripts are located just before the closing body tag -->

php dynamic dropdown menu get value

i am trying to do a dynamic dropdown menu, i manage to retrieve the first menu value but i can't manage to retrieve the second menu value.
HTML part
<div>
<label for="marca">Marca </label>
<select type="text" id="marca" name="marca" onChange="getModel()">
<option value="">Alege Marca</option>
<?php while($row = mysqli_fetch_assoc($resultMarca)){ ?>
<option value="<?php echo $row["id"] ?>"> <?php echo $row["nume_marca"] ?> </option>
<?php } ?>
</select>
</div>
<div id="model_masina">
<label for="model">Model </label>
<select id="model" nume="model">
<option value="">Alege Model</option>
</select>
</div>
Ajax Part
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type ="text/javascript">
function getModel(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","get_model.php?marca="+document.getElementById("marca").value, false);
xmlhttp.send(null);
document.getElementById("model_masina").innerHTML=xmlhttp.responseText;
}
function model_schimba(){
$modelSc = (document.getElementById("model").value);
}
</script>
PHP
?>
<label for="model">Model </label>
<select id="model" nume="model" onchange='model_schimba()'>
<option value="">Alege Model</option>
<?php
while($row = mysqli_fetch_array($res)){ ?>
<option value="<?php echo $row["id"] ?>"> <?php echo $row["name"] ?> </option>
<?php }
?> </select> <?php
}
i mange to take the variable here
$modelSc = (document.getElementById("model").value);
but when i push the submit button i can't reach the variable
$model = $_POST["model"];
"but when i push the submit button i can't reach the variable $model = $_POST["model"];"
nume="model"
PHP syntax is English-based, not in your language.
You need to change it to name="model".
The "name" attribute is the same in any language.
Having use PHP's error reporting, it would have thrown you an undefined index notice.
http://php.net/manual/en/function.error-reporting.php
First, code separation is important for readability.
Second, I think your AJAX return
document.getElementById("model_masina").innerHTML=xmlhttp.responseText;
is mistakenly pointing at a <div> container instead of the <select> list. Should be,
document.getElementById("model").innerHTML=xmlhttp.responseText;
because you are outputting select menu <option>

Show/hide select values based on previous select choice

I have 2 select's inside a form. The second select has about 2000 lines in total coming out of my mysql table. One of the column into that mysql has 1 of the values used into the first select. I want to be able to filter on that value when it is selected into the first select, so that it only shows these articles.
code now:
<div class="rmaform">
<select name="discipline" class="discipline">
<option value=" " selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article">
<?php
$articleselect = $dbh->prepare('SELECT * FROM articles');
$articleselect->execute();
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
</select>
I think i have to use Javascript for it but how do you combine PHP and Javascript? And what would be the best way to make the filter work?
jQuery for the change event and AJAX
$(document).ready(function(e) {
$('select.discipline').change(function(e) { // When the select is changed
var sel_value=$(this).val(); // Get the chosen value
$.ajax(
{
type: "POST",
url: "ajax.php", // The new PHP page which will get the option value, process it and return the possible options for second select
data: {selected_option: sel_value}, // Send the slected option to the PHP page
dataType:"HTML",
success: function(data)
{
$('select.input-article').append(data); // Append the possible values to the second select
}
});
});
});
In your AJAX.php
<?php
if(isset($_POST['selected_option']))
$selected_option=filter_input(INPUT_POST, "selected_option", FILTER_SANITIZE_STRING);
else exit(); // No value is sent
$query="SELECT * FROM articles WHERE discipline='$selected_option'"; // Just an example. Build the query as per your logic
// Process your query
$options="";
while($query->fetch()) // For simplicity. Proceed with your PDO
{
$options.="<option value='option_value'>Text for the Option</option>"; // Where option_value will be the value for you option and Text for the Option is the text displayed for the particular option
}
echo $options;
?>
Note: You can also use JSON instead of HTML for much simplicity. Read here, how to.
First give both of the selects an unique ids...
<div class="rmaform">
<select name="discipline" class="discipline" id="discipline">
<option value="" selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article" id="article">
<option value="" selected></option>
</select>
Now you can use jQuery Ajax call to another file and get the HTML Response from that file and Populate in the select field with id="article" like this...
<script type="text/javascript">
$(document).ready(function(){
$("#discipline").change(function(){
var discipline = $(this).val();
$.post(
"ajax_load_articles.php",
{discipline : discipline},
function(data){
$("#article").html(data);
}
)
});
});
</script>
Now create a new file like ajax_load_articles.php... in the same directory where the html file exists... You can place it anywhere but then you have to change the $.post("url", the url to the ajax submission.
Contents of ajax_load_articles.php :
<?php
$discipline = $_POST["discipline"];
$articleselect = $dbh->prepare("SELECT * FROM articles WHERE colname = '{$discipline}'");
$articleselect->execute();
echo '<option value="" selected></option>';
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
Now when ever you will change the select of the first select field an Ajax call will take place and the data of the second select field will automatically adjust to related data selected in the first select field.
This is an example where you can select the college specific to the state ..
Form.php
// your code for form ...
// select box for state starts
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">State</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="statename" id="stateid">
<option value="">---- Select ----</option>
<?php
$state=sql::readResultArray("Your Query To select State`");
foreach($state as $s){
?>
<option value="<?php echo $s?>"> <?php echo $s ?> </option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">Colleges</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="mycollegename">
<option value="">--- Select --- </option>
</select>
</div>
</div>
// further code for from in form.php..
Script to find the state and then pass the value to find the respective colleges in that state
<script>
$(document).ready(function(e) {
$('#stateid').change(function()
{ ids=$('#stateid').val();
$.get('mycollege.php', {type:ids} ,function(msg){
$('select[name="mycollegename"]').html(msg);
});
});
});
</script>
Call this file through ajax .. Code on this file
mycollege.php
<?php
require('db.php'); // call all function required, db files or any crud files
$type=$_GET['type'];
if(!empty($type)){
$r=sql::read("Your Query To call all teh college list");
?>
<select name="mycollegename">
<option value="">Select One</option>
<?php
foreach($r as $r){
echo "<option value=\"$r->collegename\">$r->collegename </option>";
}
?>
</select>
<?php }else{ ?>
<select name="mycollegename">
<option value="">Select State</option>
</select>
<?php } ?>

JavaScript count in line with PHP loop

I have a page with two drop-down menus. The option selected in the first drop-down menu controls what is displayed in the second.
The code was nice and easy when the drop-down menus were only used once - but I'm looking to repeat each set of drop-down menus four times.
Drop-down menu one is assigned the ID experience[<?php echo $i; ?>][manufacturer]. Drop-down menu two is assigned the ID experience[<?php echo $i; ?>][type].
Essentially, what I've got is:
<select id="experience[1][manufacturer]">...</select>
<select id="experience[2][manufacturer]">...</select>
<select id="experience[3][manufacturer]">...</select>
<select id="experience[4][manufacturer]">...</select>
... followed by:
<select id="experience[1][type]">...</select>
<select id="experience[2][type]">...</select>
<select id="experience[3][type]">...</select>
<select id="experience[4][type]">...</select>
I'm wondering: what's the best way to get the equivalent of <?php echo $i; ?> into the chunk of JavaScript that's used to output the contents of the second drop-down menu? (I know I can't use PHP directly within JavaScript like this - I just left the <?php echo $i; ?> snippets to indicate where I need to output numbers 1, 2, 3, 4 etc.
Thanks for your help!
Code:
<form>
<?php
$i=1;
while($i<=4) {
?>
<select id="experience[<?php echo $i; ?>][manufacturer]">
<option value="Ford">Ford</option>
<option value="Honda">Honda</option>
<option value="Mercedes">Mercedes</option>
</select>
<select id="experience[<?php echo $i; ?>][type]">
<script type='text/javascript'>
$(document).ready(function() {
$("#experience[<?php echo $i; ?>][manufacturer]").change(function() {
$("#experience[<?php echo $i; ?>][type]").load("get_type.php?choice=" + $("#experience[<?php echo $i; ?>][manufacturer]").val());
});
});
</script>
</select>
<?php
$i++;
}
?>
</form>
Revised code:
<form>
<script type='text/javascript'>
$(document).ready(function() {
$(".experienceManufacturer").change(function() {
$("#experience["+$(this).attr('data-id')+"][type]").load("get_type.php?choice=" + $(this).val());
});
});
</script>
<?php $i=1;
while($i<=4) { ?>
<select id="experience[<?php echo $i; ?>][manufacturer]" class="experienceManufacturer" data-id="<?php echo $i; ?>">
<option value="Ford">Ford</option>
<option value="Honda">Honda</option>
<option value="Mercedes">Mercedes</option>
</select>
<select id="experience[<?php echo $i; ?>][type]">
</select>
<?php
$i++;
}
?>
</form>
You should not need to include the script element in your PHP loop.
Instead, you should add a similar class to all common select elements. Something like class="experience"
Then, with a single script element you can attach events to all the selects:
<script type='text/javascript'>
$(document).ready(function() {
$("select.experience").each(function(i,element){
// here element is the actual item from the selected set, i is its index
$(element).on("change", function() {
$("#experience[" + i + "][type]").load("get_type.php?choice=" + $(element).val());
});
});
});
</script>
Instead of repeating the same javascript code 4 times, put it outside your loop and give classes to your select elements and use them as selectors for your jquery code. You could then add an attribute (named data-id for example) to your select elements containg their ids. It would look something like this
<select id="experience[<?php echo $i; ?>][manufacturer]" class="experienceManufacturer" data-id="<?php echo $i; ?>">
<option value="Ford">Ford</option>
<option value="Honda">Honda</option>
<option value="Mercedes">Mercedes</option>
</select>
<select id="experience[<?php echo $i; ?>][type]"></select>
And your javascript code (outside the loop) would look something like this
$(document).ready(function() {
$(".experienceManufacturer").change(function() {
$("#experience\\["+$(this).attr('data-id')+"\\]\\[type\\]").load("get_type.php?choice=" + $(this).val());
});
});
Note that I used the keyword "this" inside the change event which references to the select element.
Edit: Added backslashes to escape the brackets in the jQuery selector (or else jQuery interprets it as an attribute).

Display php using javascript

<p>Todays Date: <? echo $date; ?></p>
<p>Are you applying for a day, evening, or weekend class?
<select name='date' id='wclass'>
<option value ='day'> Day</option>
<option value ='evening'>Evening</option>
<option value ='weekend'>Weekend</option>
</select>
Program Start Date:
<div id='dates'></div>
<script language="javascript">
$(document).ready(function() {
{ setInterval(function () {
if ($("#wclass").val()=='day')
{ $('#dates').html("<? echo <select name='date'>
<option value ='date1'> $start1 </option>
<option value ='date2'>$start2</option>
<option value ='date3'>$start3</option>
<option value ='date4'>$start4</option>
<option value ='date5'>$start5</option>
<option value ='date6'>$start6</option>
<option value ='date7'>$start7</option>
</select> }?>");}
}, 1000);
});
My issue is that i am not sure how to display php using javascript. The variables are all correct, the issue is to get the php to display as html would in my .html. All i want to do is display the php variables which i fetched in the beginning. So the variables have been defined in php now i want to turn them into a html list based on my javascript. You may notice that the echo is missing quotes, thats because i dont know how to put quotes, i cant use " or ' because they both interup quotes that are already there.
Your javascript does not have access to your PHP variables, unless you request them via AJAX.
However, you don't have to use AJAX. You could use your PHP code to build the Javascript code before it is sent to the browser!!
Here's one way of doing it:
<?php
$start1 = '01/01/2010';
$start2 = '11/11/2010';
$start3 = '03/12/2010';
// and so on...
?>
<p>Today's Date: <?php echo $date; ?></p>
<p>Are you applying for a day, evening, or weekend class?</p>
<select name="date" id="wclass">
<option value="day">Day</option>
<option value="evening">Evening</option>
<option value="weekend">Weekend</option>
</select>
Program Start Date:
<div id="dates"></div>
<script language="javascript">
$(document).ready(function() {
{
$("#wclass").change(function ()
{
if( $(this).val() == 'day' )
{
$('#dates').html('<select name="date">\
<option value="date1"><?php echo $start1; ?></option>\
<option value="date2"><?php echo $start2; ?></option>\
<option value="date3"><?php echo $start3; ?></option>\
<option value="date4"><?php echo $start4; ?></option>\
<option value="date5"><?php echo $start5; ?></option>\
<option value="date6"><?php echo $start6; ?></option>\
<option value="date7"><?php echo $start7; ?></option>\
</select>');
}
});
});
</script>
An even better option would be to just create the second select outright, and then show/hide it when needed:
<?php
$start1 = '01/01/2010';
$start2 = '11/11/2010';
$start3 = '03/12/2010';
// and so on...
?>
<p>Today's Date: <?php echo $date; ?></p>
<p>Are you applying for a day, evening, or weekend class?</p>
<select name="date" id="wclass">
<option value="day" selected="selected">Day</option>
<option value="evening">Evening</option>
<option value="weekend">Weekend</option>
</select>
Program Start Date:
<select id="dates" name="date">
<option value="date1"><?php echo $start1; ?></option>
<option value="date2"><?php echo $start2; ?></option>
<option value="date3"><?php echo $start3; ?></option>
<option value="date4"><?php echo $start4; ?></option>
<option value="date5"><?php echo $start5; ?></option>
<option value="date6"><?php echo $start6; ?></option>
<option value="date7"><?php echo $start7; ?></option>
</select>
<script language="javascript">
$(document).ready(function() {
{
$("#wclass").change(function ()
{
$(this).val() == 'day' ? $('#dates').show() : $('#dates').hide()
});
});
</script>
PHP is a server-side language. PHP is executed by the server, and the result (usually some HTML) is sent to the client for display. If you're trying to display PHP code literally, then it's definitely possible. I get the feeling, however, that you're trying to execute the PHP code in Javascript. You can't do that, because Javascript is executed client-side -- that is, after the page has already been sent to the client's browser from the server.
Do you understand completely, the difference between running scripts on server vs running HTML/JavaScript on web-client ?
PHP is executed on server. It renders HTML and JS. Then HTML/JS goes to a viewer (web-client) and is executed on client's machine... You can't "run PHP inside JS" the way you want.
If you need some data from PHP injected to your JS code you may try running AJAX.
Checklist of simple, simple things that we don't want to overlook:
You saved the file with a .php extension.
Short tags are enabled.
That should work. Make sure it's saved as a .php file, and you should be good. Oh, and preferably you'd use <?php .. ?> instead of <? ?> since shorttags are advised against for compatibility reasons.
Note If your PHP was actually executing, you'd be getting syntax errors thrown into your page because your echo doesn't have the string in quotes, among other things.

Categories