I currently have an issue with my drop down menu using JavaScript/AJAX and PHP.
Here's the code for the edit.php file which is supposed to retrieve data from multiple selection boxes in a drop-down list:
<td ><input readonly type="text" id="mainlines" value='<?php echo $_SESSION["mainlines"];?>' name="mainlines"/> </td>
<td ><input readonly type="text" id="categories" value='<?php echo $_SESSION["categories"]; ?>' name="categories"/> </td>
<td>
<select name="subcategories" id="menu" onChange="SelectAccountHead_Code(this.value)">
<option value="<?php print $subcategories; ?>"><?php print $subcategories; ?></option>
<?php
$sql1a = "SELECT * FROM subcategory ORDER BY subcategories asc";
$smt1a = $dbs->prepare($sql1a);
$smt1a -> execute();
while($row1a=$smt1a->fetch(PDO::FETCH_ASSOC))
{
if($row1a['subcategories']==$_GET['id2'] )
echo ("<option selected value=$row1a[subcategories]>$row1a[subcategories]</option>");
else
echo ("<option value=$row1a[subcategories]>$row1a[subcategories]</option>");
}
?>
</select>
</td>
For the "mainlines" and "categories", I get the data showing output only when it is selected, but when the item is being edited it doesn't automatically print it out unless I use "print $mainlines" or "print $categories".
How do I insert the onChange event changer in the if/else statement?
I want it to state the following in pseudo-code:
if (onChange = "SelectAccountHead_Code(this.value)"){
print $mainlines;
} else {
echo $_SESSION["mainlines"];
}
How do I go about inserting the correct syntax in the if/else clause with regards to the JavaScript/AJAX event changer/handler?
Update:
Here's my JavaScript code - where am I missing the AJAX code?
function SelectAccountHead_Code(i)
{
var k=document.getElementById("menu").selectedIndex;
var l=document.getElementById("menu1").selectedIndex;
if((k>0)&&(l>0))
{
self.location="edit3.php?productsnames=<?php print $productsnames;?>&id="+document.getElementById("menu").options[k].value+"&id2="+document.getElementById("menu").options[k].innerHTML +"&id3="+document.getElementById("menu1").options[l].value+"&id3="+document.getElementById("menu1").options[l].innerHTML;
}
}
function SelectAccountHead_Codes(j)
{
var k=document.getElementById("menu").selectedIndex;
var l=document.getElementById("menu1").selectedIndex;
if((k>0)&&(l>0))
{
self.location="edit3.php?productsnames=<?php print $productsnames;?>&id="+document.getElementById("menu").options[k].value+"&id2="+document.getElementById("menu").options[k].innerHTML +"&id3="+document.getElementById("menu1").options[l].value+"&id3="+document.getElementById("menu1").options[l].innerHTML;
}
}
function SelectUp(i)
{
var k=document.getElementById("menuUp").selectedIndex;
var l=document.getElementById("menuUp").selectedIndex;
self.location="edit3.php?id="+document.getElementById("menuUp").options[k].value+"&id2="+document.getElementById("menu").options[k].innerHTML +"&id3="+document.getElementById("menu1").options[l].value+"&id3="+document.getElementById("menu1").options[l].innerHTML;
}
function SelectUp(j)
{
var k=document.getElementById("menuUp").selectedIndex;
var l=document.getElementById("menuUp").selectedIndex;
self.location="edit3.php?id="+document.getElementById("menuUp").options[k].value+"&id2="+document.getElementById("menu").options[k].innerHTML +"&id3="+document.getElementById("menu1").options[l].value+"&id3="+document.getElementById("menu1").options[l].innerHTML;
}
You cant combine Javascript and PHP without further requests (Ajax) and server interaction.
Other big mistake:
echo ("<option selected value=$row1a[subcategories]>$row1a[subca.........
you have constants in your associative arrays.
See this example why this is wrong:
$array = array('test' => 111);
define('test', 999);
echo $array[test];
proper:
echo ("<option selected value='" . $row1a['subcategories'] . "'>" . $row1a['su..
// consider adding htmlspecialchars() or addslashes() to your output
More minor mistakes / bad practice:
onChange should be all small letters: onchange
if .. else block should have { }
Related
<body>
<H1>4a</H1>
<form action="hw4b.php" method="post">
<?php
$con = mysqli_connect("localhost","[credential]","","[credential]")
or die("Failed to connect to database " . mysqli_error());
?>
<select name="id" value="id">
<script>
for (x=1;x<=101;x++)
{
document.write("<option value="+x+">"+
<?php echo mysqli_query($con, "SELECT LASTNAME FROM CUSTOMERS WHERE CUSTOMERID == "+x+";")?>
+"</option>");
}
</script>
</select>
<input type="submit" value="SEND IT">
</form>
</body>
So this should put the corresponding LASTNAME into the select, but it just fills every row with "NaN". I'm sure this is some stupid minor error, but I've been staring at it too long.
you should query the results of mysqli_query
do something like this:
<select name="id" value="id">
<?php
$query = mysqli_query($con, "SELECT LASTNAME FROM CUSTOMERS WHERE WHERE CUSTOMERID >=1 and CUSTOMERID <= 101 ;");
while ($row = mysqli_fetch_array($query))
echo "<option id='".$row['LASTNAME']."'>".$row['LASTNAME']."</option>";
?>
</select>
notes:
no need for javascript usage
please escape the query parameter
id of the option is the value that will be sent to the server, makes more since to send LASTNAME
avoid using a query at a loop
Note that your for cycle is in javascript (between <script> tags), yet you try to fill in some data in php.
Everything in PHP happens on server side, i.e. is interpreted, packed into a http response and returned to the client, where it is unpacked and javascript is executed.
You need to either put both into javascript, or both into php.
<select>
<?php
for ($i = 0; $i < 100; i++){
///make some select here
echo "<option value="$i"> ...output the select </option>"
}
?>
</select>
This way, all options are generated on server side and transferred to client as text
<select>
<option value="0">...</option>
<option value="1">...</option>
...
Other option is to export the database data into javascript, and then access it in javascript.
<script>
//or perhaps better
var myOtherData = <?=json_encode($somePHPData)?>;
</script>
//now you can use for loop with document.write and one of the variables you exported...
You need to be very careful and sure which execution happens on server, and which on client side.
There are several issues I think. You are using a comparison operator in the SELECT statement, it should just be =, not ==. Also, mysqli_query returns a mysqli_result, not a value like "Johnson" for LASTNAME. And, maybe most importantly, it doesn't make sense to do this with javascript since you're writing the values to the document before sending it to the browser anyway.
The code should look something like this (not tested)
<select name="id" value="id">
<?php
$query = 'SELECT LASTNAME, CUSTOMERID FROM CUSTOMERS WHERE CUSTOMERID >= 1 AND CUSTOMERID <= 101 ORDER BY CUSTOMERID ASC';
$result = mysqli_query($con, $query);
if (!$result) {
echo 'some error handling';
} else {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row['CUSTOMERID'] . '">' . $row['LASTNAME'] . '</option>';
}
}
?>
</select>
Please need a help on how to call the current select color to the selective item in the dropdown.
dropdown:
database:
php code:
<select data-placeholder="Escolha Categoria..." class="select-search" name="categoria_id" tabindex="2" id="category_drop">
<option value="">Categoria</option>
<?php foreach($categorias_produtos as $categoria_produto){ ?>
<option value="<?php echo $categoria_produto->categoria_id; ?>"><?php echo $categoria_produto->categoria_nome; ?></option>
<?php } ?>
</select>
js code:
<script>
function format(produto) {
if (!produto.id) return produto.text; // optgroup
return "<em class='fa fa-circle space_for_product' style='color:<?php
foreach($categorias_produtos as $categoria_produto){
echo $categoria_produto->categoria_cor;
}
?>'></em>" + produto.text;
}
$("#category_drop").select2({
formatResult: format
});
and this is the result:
<div class="select2-result-label"><em class="fa fa-circle space_for_product" style="color:#ff0040;#ff4000;#00ff40;#00bfff;#ffff00;#bfff00;#4000ff;#ffbf00;#ff00bf;"></em>Farinhas</div>
so how to call just the correct color from database for each item in dropdown ?
to be interpreted PHP code must pass through the server.
for javascript, it's the console inside the browser who does it. So if you put some php inside Js code. it won't work.
the solution is to get the colors first and write them in an invisible block with an id then get the values later by javascript
<?php
echo '<div id="colors" display = "none">';
foreach ($ categorias_produtos as $ categoria_produto) {
echo "$ categoria_produto-> categoria_cor"." ,";
}
echo '</ div>';
?>
then you will use :
<script>
colorString = document.getElementById("colors").value;
colorArray = colorString.split(",");
</script>
i wish that was usefull for you. good day.
I'm sorry to ask a duplicate question again but i'm really got into this...
Down there is my code:
<script type="text/javascript">
function textHint()
{
Confirm("Do u want to proceed");
}
</script>
<select name="duration" id="duration" class="inp_bx" onChange="textHint();">
<option value="1">-Select-</option>
<?php
$sql = "select distinct(package_type) from tbl_package";
$retval = mysql_query($sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
echo 'Could not get data: ' . mysql_error();
}
while($row = mysql_fetch_assoc($retval,MYSQL_ASSOC))
{
$package= $row['package_type'];?>
<option value="<?php echo $package?>"><?php echo $package;?>
</option>
<?php } ?>
</select>
I'm getting the value in select box from database but the onchange function is not triggering out...i dont know why?
This is similar to the one on the link:
call javascript function onchange event of dropdown list
Instead the value is fetched from the database...
Thanks in advance guys...
Javascript is case-sensitive. Your Confirm should be confirm.
function textHint()
{
confirm("Do u want to proceed");
}
Hi I am trying to create a set of drop down boxes that will use an array of data from the values that you pick and then runs through a loop to post them to the screen at the moment the data that i want to use will just be local but i want to edit this later so that it will loop through the data from my database and post that to the screen. i have looked at other questions on this subject and just wondering how i would change it for my code i have looked at this link questions on stack overflow that I have looked at i have just got a couple questions that im wondering if anybody has seen this before or if they have seen any examples i have also looked at for loops and i understand the concept
my questions to you are:
1) how would I post the values from my drop down boxes into a php array
2) how would I then check the values against and array of data and then choose which are correct and post them to the screen.
3)Would I need to use a second language like javascript or can it be done just in php
My drop down box code is
<div id="Content">
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
Choose a type:<br />
<select id="type">
<option value="%">any...</option>
</select>
<br /><br />
Choose a principle:<br />
<select id="principle">
<option value="%">any...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
<!-- end of the Options -->
below is the select.class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowCategory()
{
$sql = "SELECT * FROM subject";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['subject_id'] . '">' . $row['description'] . '</option>';
}
return $category;
}
public function ShowType()
{
$sql = "SELECT * FROM section WHERE subject_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['section_id'] . '">' . $row['description'] . '</option>';
}
return $type;
}
public function ShowPrinciple()
{
$sql = "SELECT * FROM principle WHERE section_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$principle = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$principle .= '<option value="' . $row['principle_id'] . '">' . $row['description'] . '</option>';
}
return $principle;
}
}
$opt = new SelectList();
?>
1) how would I post the values from my drop down boxes into a php array
In the form tag add method="POST". Reference in PHP with $_POST array. Make sure to validate and escape the data before writing to your DB.
2) how would I then check the values against and array of data and then choose which are correct and post them to the screen.
If you don't have millions of categories, you are better off sending them all as a JSON array and using Javascript. Something like:
<script>
var categories = <?php echo json_encode($opt->ShowCategory()); ?>;
</script>
json_encode may require some options to be set, depening on your character set. More info here: http://php.net/manual/en/function.json-encode.php
Making a new request each time someone changes a dropdown box will drive them crazy, I know I hate that. If you have used jQuery before, this is very easy. This isn't that difficult without it.
3)Would I need to use a second language like javascript or can it be done just in php
For the sake of your users, use Javascript.
code for showCategory()
...
$categories = new array();
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$categories[$row['subject_id']] = $row['description'];
}
$validCategories = $this->getValidCategories() // get the valid categories
foreach($categories as $index=>$cat){
// only choose the categories that are valid
if(array_search($cat,$validCategories) !== FALSE)
$category.= '<option value="'.$index.'">'.$cat.'</option>';
}
return $category;
I am trying to change a drop down so that a user can add a custom input instead.
I am using VQMod and have currently set up a PHP array as follows:
<td><select name="electricColours">
<?php foreach (array("", "White", "Black", "Add Custom Colour..." ) as $eColours) { ?>
<?php if ($electricColours == $eColours) { ?>
<option value="<?php echo $eColours;?>" selected="selected"><?php echo $electricColours; ?></option>
<?php } else { ?>
<option value="<?php echo $eColours;?>"><?php echo $eColours; ?></option>
<?php }?>
<?php } ?>
<td class="left"><a onclick="AddCustomColour();" class="button"><?php echo "Add Custom Colours"; ?></a></td>
</select>
How would I be able to add new values to the eColours using the "Add Custom Colour..." so that the user inputs something and that colour is added on to the array.
I thought using Javascript so that it shows up as an alert and the user gets to choose their option would work however it keeps saying the variable is not defined.
<SCRIPT TYPE="text/javascript">
function AddCustomColour()
{
var colour=prompt("Please add custom colour","Silver");
var arrays = <?php echo json_encode($electricColours); ?>;
if (colour!=null)
{
electricColours.push(colour);
}
}
</SCRIPT>
Thanks
Use the DOM API:
var option = document.createElement("option");
option.setAttribute("value", value);
option.appendChild(document.createTextNode(value));
document.getElementById("the_select_element").appendChild(option);
Instead of:
document.getElementById("the_select_element")
You could do something like:
document.forms.the_form.electricColours
replace this code
<SCRIPT TYPE="text/javascript">
function AddCustomColour()
{
var colour=prompt("Please add custom colour","Silver");
var arrays = <?php echo json_encode($electricColours); ?>;
if (colour!=null)
{
electricColours.push(colour);
}
}
</SCRIPT>
With this Code
<script type="text/javascript">
function AddCustomColour()
{
var colour=prompt("Please add custom colour","Silver");
var ob = $("#electricColours");
if (colour!=null)
{
ob.prepend("<option value="+ val +">" + text + "</option>");
}
}
</script>