Javascript Drop-Down with PHP Function? - javascript

I am using this code I found to try and make this drop down menu.
http://www.javascriptkit.com/script/cut183.shtml
Ignore my variables and values, they are all place holders.
The problem is, it calls the value in Javascript, but I want to call a specific function in PHP depending on what option in the menu you chose.
<html>
<body>
<form name="doublecombo" form action"index.php" method="POST">
<p><select name="example" size="1" onChange="redirect(this.options.selectedIndex)">
<option>Amazon</option>
<option>Apple</option>
<option>Logitech</option>
<option>Nike</option>
</select>
<select name="stage2" size="1">
<option value="http://javascriptkit.com">Kindle Fire</option>
<option value="http://www.news.com">Kindle DX</option>
<option value="http://www.wired.com">Kindle Charger</option>
<option value="http://www.microsoft.com">Kindle Paperweight</option>
</select>
<input type="button" name="test" value="Generate"
onClick="gen()">
</p>
<script>
var groups=document.doublecombo.example.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=new Option("Kindle Fire","http://javascriptkit.com")
group[0][1]=new Option("Kindle DX","http://www.news.com")
group[0][2]=new Option("Kindle Charger","http://www.wired.com")
group[0][2]=new Option("Kindle Paperweight","http://www.microsoft.com")
group[1][0]=new Option("MacBook","http://www.cnn.com")
group[1][1]=new Option("iPhone","http://www.abcnews.com")
group[1][2]=new Option("iPad","http://www.yahoo.com")
group[1][3]=new Option("iMac","http://www.apple.com")
group[2][0]=new Option("G602 Wireless Gaming Mouse","http://www.hotbot.com")
group[2][1]=new Option("G19s Gaming Keyboard","http://www.infoseek.com")
group[2][2]=new Option("G430 Surround Sound Gaming Headset","http://www.excite.com")
group[2][3]=new Option("PowerShell Controller","http://www.lycos.com")
group[3][0]=new Option("Nike FuelBand","http://www.nike.com")
var temp=document.doublecombo.stage2
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function gen(){
location=temp.options[temp.selectedIndex].value
}
</script>
<?
function kindlegen(){
?>
<textarea name="message" placeholder="CODES" rows="10">
<?
{ $amount = "5"; $i = 1; while ($i <= $amount)
{ $rand_letter1 = substr(str_shuffle("123456789"), 0, 2); $ran = rand(1, 6); echo "D0FB A0A0 343".$ran." 0A".$rand_letter1."\n"; $i++; } } ?>
</textarea>
<?
}
?>
</form>
</html>
</body>

PHP is executed server side, HTML and Javascript client side.
This means no, there is no way you can execute PHP inside your Javascript (never ever).
You can only post information back to the server, via ajax, which allows you to make further operations. When these are finished on the server, your ajax call receives the result and returns it back to the client for further processing.

Related

Filter Dropdown Based on Another Dropdown Selection

I have multiple dropdowns and want to filter the contents of the second dropdown based on what is selected in the first dropdown. Here is the following code that I have so far. How could I do this?
HTML/PHP:
<td>
<select id="major" onChange="updateCat();">
<?php foreach ($dropdown_major->fetchAll() as $drop_major): ?>
<option
value=""
data-name="<?php echo $drop_major ['Major Category'];?>"
>
<?php echo $drop_major ['Major Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<select id="minor">
<?php foreach ($dropdown_minor->fetchAll() as $drop_minor): ?>
<option
value=""
data-name="<?php echo $drop_minor ['Minor Category'];?>"
>
<?php echo $drop_minor ['Minor Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
JavaScript:
function updateCat() {
var e = document.getElementById("major");
var majorSelected = e.options[e.selectedIndex];
document.getElementById("minor").value = majorSelected.dataset.name;
}
Database connection and SQL statements:
<?php
$host="xxxxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxxxx";
$dbPass="xxxxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql_major = "SELECT DISTINCT [Major Category] FROM ProductTable ORDER BY [Major Category] ASC";
$sql_minor = "SELECT DISTINCT [Minor Category] FROM ProductTable ORDER BY [Minor Category] ASC";
$dropdown_major = $dbh->query($sql_major);
$dropdown_minor = $dbh->query($sql_minor);
?>
Sorry don't have much time can't make your answer for your code but giving you an example which will surely help you. run snippet below.
HTML
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br>
<select id="second"></select>
and Javascript
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
this code will work for you but try to use JSON for sending options to user and then apply some if else statement according to user selection of first drop down.
Tip: If you have large no. of options in select statement or large no. of select statements in your code then go and learn AJAX First. its easy and simple you can learn it easily. JSON and AJAX hardly takes 2-3 days.In Ajax call function according to user selection and send data using JSON. Although Ajax increases no. of request to server but it will decrease code length. which decreases page load time, easy to maintain, and good for search engine. Google love pages with less code and more information and will help you in future too to solve lots of problems easily.
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br><br>
<select id="second"></select>

Unable to send two strings together using PHP to JavaScript

I'm trying to pass database value javascript / ajax. If if send directly it works well,
The same I'm trying to do from database. And some how it doesn't work.
I'm sending value of the option to script like this,
<select name="users" onchange="showUser(this.value)">
and when I send value directly like this, It show the correct value in script.
<option value="Peter Grif">Peter Griffin</option>
Script Result is = Peter Grif
And if the same I fetch from database, like this.
while($row=$select->fetch_assoc())
{
echo "<option value=".$row['name'].">".$row['name']."</option>";
}
In Dropdown box it is exactly working with full name like "Peter Grif"
But the script result is = "Peter" the second part of name after space never comes.
Full Program:
<html>
<head>
<script>
function showUser(str) {
window.alert(str);
}
</script>
</head>
<body>
<body>
<form>
<center> <select name="users" onchange="showUser(this.value)"> </center>
<option value="Peter Grif">Peter Griffin</option>
<option value="Lois Griff">Lois Griffin</option>
<?php
include("connection.php");
$select=$con->query("select name from users group by name");
while($row=$select->fetch_assoc())
{
echo "<option value=".$row['name'].">".$row['name']."</option>";
}
?>
</select>
</form>
<br>
</body>
</html>
I modified your code in while loop and it works as you want. Its the quotation issue.
<html>
<head>
<script>
function showUser(str) {
window.alert(str);
}
</script>
</head>
<body>
<body>
<form>
<center> <select name="users" onchange="showUser(this.value)"> </center>
<option value="Peter Grif">Peter Griffin</option>
<option value="Lois Griff">Lois Griffin</option>
<?php
include("connection.php");
$select=$con->query("select name from users group by name");
while($row=$select->fetch_assoc())
{
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
?>
</select>
</form>
<br>
</body>
</html>
echo "<option value=".$row['name'].">".$row['name']."</option>";
The option value needs to be quoted. You are ending up with
<option value=Peter Grif>Peter Grif</option>
It needs to be quoted so it ends up like
<option value='Peter Grif'>Peter Grif</option>
So either
echo "<option value='".$row['name']."'>".$row['name']."</option>";
or perhaps
echo "<option value='{$row['name']}'>{$row['name']}</option>";
(you can reference arrays within double quotes by surrounding by curly brackets, I feel it makes it easier to read than concatenation, so you don't get quote confused when echoing HTML especially, but it's just my preference).
Doing view source on page can help with these things to make sure the generated HTML is valid.

Check for form value to use as a condition without having to submit form

I have been using this code:
<html>
<head>
<script>
function validatePfin() {
var x1 = document.forms["pfin"]["cash"].value;
var x2 = document.forms["pfin"]["all_assets"].value;
var x3 = document.forms["pfin"]["all_debt"].value;
if (x1 == null || x1 == "") {alert("Please enter Cash Amount.");}
else {
if (x2 == null || x2 == "") {alert("Please enter Non-Cash Assets.");}
else {
if (x3 == null || x3 == "") {alert("Please enter Total Debt.");}
else {
document.getElementById('sub1').value='Processing, please wait ... ';
document.getElementById('sub1').disabled=true;
form.submit();
}}}
return false;
}
</script>
</head>
<body>
<table>
<form method="POST" name="pfin" autocomplete="on" target="vframe" action="p_financials_s.php" enctype="multipart/form-data" onsubmit="return validatePfin()">
<tr><td>
<select name="cash" id="cash">
<option value="<?php echo $row['cash'];?>" selected><?php echo $row['cash'];?></option>
<option value="">Select</option>
<option value="0" >0</option>
<option value="1000" >1000</option>
</select>
<tr><td>
<select name="all_assets" id="all_assets">
<option value="<?php echo $row['all_assets'];?>" selected><?php echo $row['all_assets'];?></option>
<option value="">Select</option>
<option value="0" >0</option>
<option value="1000" >1000</option>
</select>
<tr><td>
<select name="all_debt" id="all_debt">
<option value="<?php echo $row['all_debt'];?>" selected><?php echo $row['all_debt'];?></option>
<option value="">Select</option>
<option value="0" >0</option>
<option value="1000" >1000</option>
</select>
<tr><td>
<input type="submit" id="sub1" class="back1" value="Save And Go To Next Step >">
</table>
</form>
</body></html>
This is a pared down snip from the code. What it does is that upon submission, the form checks to see if the fields have values and if not stops the submission.
What I am trying to figure out is how, using PHP/javascript (or ?), I can 'read' a form field, check to see if it has a value, and make that a variable for a conditional statement, w/o having to submit and post to the DB.
For example, let's say I want the "cash" value to have a value, and if that is true, then I can make that a condition to, let's say, display a link:
<?
$cash1 = form.field.not-yet-sumbitted.cash
if( $cash1 != "") {
echo "http://examplesite.com";
}
?>
I have tried using an onchange event in javascript to somehow bring the "cash" variable into memory, and then once done, somehow have the PHP variable pick it up, but that doesn't fire.
Since you are submitting the form as POST to p_financials_s.php, on that file you can simple get the value of any field from the global $_POST array. e.g.
$field1 = $_POST['field1'];
and then you can simply add a check on that field. You can add validation on javascript end if you just want to validate things and then submit the form.
What you're aiming for is best done through AJAX calls in JavaScript due to their client-sided nature and ability. PHP is a server-sided language meaning that without submitting the <form> (to itself at the very least) there would be no way for PHP to interpret it.
A common methodology is to implement the jQuery library's $.ajax() functionality, effectively allowing you to POST or GET information to/from a PHP script without having to leave the page or submit the form itself, such as through onclick calls.
Examples can be found in documentation here (towards the bottom of of the document): http://api.jquery.com/jquery.ajax/.

OnChange option remain same after page refresh

I have this script for money conversion so user can choose it's currency from the list like Us to Euro so I want to make it remain same after page refresh like if user have chosen Euro and he refresh the page it should remain same.
Here is my Javascript and Code
<script>
function updatePrice(val) {
p = document.getElementById("original_price").value;
newp = p * val;
document.getElementById("calculated_price").value = newp;
}
</script>
Php Code:
<?php
$pr = 180;
?>
<select onchange="updatePrice(this.value)">
<option value="1">US</option>
<option value="98">RS</option>
<option value="61">Ind</option>
</select>
<input type="hidden" id="original_price" value="<?php echo $pr; ?>" />
Price: <input type="text" id="calculated_price" value="<?php echo $pr; ?>" />
Update 1 After Implementing Session
<?php
session_start();
// store session data
$_SESSION['value']=".updatePrice(this.value).";
if(isset($_SESSION['value']));
?>
<?php
$pr = 180;
?>
<select onchange="<?php echo $_SESSION['value']; ?>">
<option value="1">US</option>
<option value="98">RS</option>
<option value="61">Ind</option>
</select>
<br>
<hr>
<input type="hidden" id="original_price" value="<?php echo $pr; ?>" />
Price: <input type="text" id="calculated_price" value="<?php echo $pr; ?>" />
<script>
function updatePrice(val) {
p = document.getElementById("original_price").value;
newp = p * val;
document.getElementById("calculated_price").value = newp;
}
</script>
Actually PHP dosent offer any viewstate mechanism, as far as i know , So what you can do is store this in some hidden field.The best way and my personal recommendation is to use a session variable for this purpose
http://www.w3schools.com/Php/php_sessions.asp
And if you need to solve this issue using javascript, You can use Cookies too
http://www.w3schools.com/js/js_cookies.asp
I have done this using jquery and javascript by setting a cookie, hence i dont want you to get confused with jquery plugin for cookie. You can do this in a much more simpler way using jquery plugin for cookie.
Here's the code
HTML
<select id="selectCurrency">
<option value="1">US</option>
<option value="98">RS</option>
<option value="61">Ind</option>
</select>
jquery/javascript
$(document).ready(function(e){
var name = "Currency=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++){
var c = ca[i].trim();
if (c.indexOf(name)==0) $('#selectCurrency').val(c.substring(name.length,c.length));
}
});
$('#selectCurrency').change(function(e){
var cookieVal = "Currency="+$(this).val();
document.cookie = cookieVal ;
});
Fiddle
http://jsfiddle.net/AmarnathRShenoy/HM3Zj/
You can use session or store the selected values somewhere in database, inUpdate price function make an ajax call which stores, your selected value and keep pdating at, on onchange event. now, each time your page gets refreshed, the previuosly selected value will get fetched from the database and you can show it seleted.

Dynamic drop down list using html and php

I'm learning html and php, I have a mysql DB employees where there is a table called Employees_hired, which stores id, name, department and type of contract. I want to make a drop down list of employees who belong to a type of department and a specific contract type. In the code would be something like:
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="<?php $_SERVER['PHP_SELF']?>">
department:
<select id="department" name="department" onchange="run()"> <!--Call run() function-->
<option value="biology">biology</option>
<option value="chemestry">chemestry</option>
<option value="physic">physic</option>
<option value="math">math</option>
</select><br><br>
type_hire:
<select id="type_hire" name="type_hire" onchange="run()"> <!--Call run() function-->
<option value="internal">Intenal</option>
<option value="external">External</option>
</select><br><br>
list of employees:
<select name='employees'>
<option value="">--- Select ---</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
$list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<?php echo $row_list['name']; ?>">
<?php if($row_list['name']==$select){ echo $row_list['name']; } ?>
</option>
<?php
}
?>
</select>
</form>
</body>
</html>
The question I have is: how to get the selected values ​​from the first drop-down lists (type_hire and department) for use in the query and fill the drop down list of employees. I know how to fill a dropdown list by querying the DB (what I learned in an online course) but I do not know how to take the values ​​from the dropdown lists and use them in my practice. I read that I can use "document.getElementById (" id "). Value" to give that value to the variable in the query, but nowhere explained in detail how. I am new to web programming and my knowledge of Javascript are poor. Can anyone tell me the best way to do this?. It is possible only using html and php or I have to use javascript?
So you have the onchange in there and that's a start. The onchange is referencing a JavaScript function that you don't show. There are a couple quick ways to approach this:
Post the form to itself (as you have chosen) or
use ajax (possibly via jQuery for quickness).
(both of these examples don't address how you are accessing the database)
1)
Using your run function:
<script type="text/javascript">
function run(){
document.getElementById('form1').submit()
}
</script>
Additional PHP:
<?php
if (isset($_POST['department']) && isset($_POST['type_hire']))
{
$value_of_department_list = $_POST['department'];
$value_of_type_hire = $_POST['type_hire'];
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");
while($row_list=mysql_fetch_assoc($list))
{
echo "<option value=\"{$row_list['name']}\">{$row_list['name']}</option>";
}
}
else
{
echo "<option>Please choose a department and a type of hire</option>";
}
?>
2)
<script type="text/javascript">
function run(){
$.post('get_employees.php',$('form1').serialize(),function(data){
var html = '';
$.each(data.employees,function(k,emp){
$('select[name="employees"]').append($('<option>', {
value: emp.name,
text: emp.name
}));
.html(html);
},"json");
}
</script>
And get_employees.php would contain something like:
<?php
if (isset($_POST['department']) && isset($_POST['type_hire']))
{
$value_of_department_list = $_POST['department'];
$value_of_type_hire = $_POST['type_hire'];
$return = array();
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");
while($row_list=mysql_fetch_assoc($list))
{
$return[]['name'] = $row_list['name'];
}
echo json_encode($return);
}
?>
Note, these are just quickly written examples. A lot more could/should be done here.
Heres a modified jQuery version of your code. (With some cleanup)
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="<? $_SERVER['PHP_SELF']?>">
department:
<select id="department" name="department" onchange="run()">
<!--Call run() function-->
<option value="biology">biology</option>
<option value="chemestry">chemestry</option>
<option value="physic">physic</option>
<option value="math">math</option>
</select><br><br>
type_hire:
<select id="type_hire" name="type_hire" onchange="run()">
<!--Call run() function-->
<option value="internal">Intenal</option>
<option value="external">External</option>
</select><br><br>
list of employees:
<select name='employees'>
<option value="">--- Select ---</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
$list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<?php echo $row_list['name']; ?>">
<? if($row_list['name']==$select){ echo $row_list['name']; } ?>
</option>
<?php
}
?>
</select>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--[ I'M GOING TO INCLUDE THE SCRIPT PART DOWN BELOW ]-->
</body>
</html>
Now I cleaned up the tags, and added a hotlink to jQuery using googleapis free cdn. Next is the actual javascript. Btw. DO NOT USE THE MYSQL_* FUNCTIONS IN PHP. They are depreciated. Check out http://php.net/manual/en/mysqlinfo.library.choosing.php for more info on that. On to the scripting...
<script type="text/javascript">
$('#type_hire').change(function() {
var selected = $('#type_hire option:selected'); //This should be the selected object
$.get('DropdownRetrievalScript.php', { 'option': selected.val() }, function(data) {
//Now data is the results from the DropdownRetrievalScript.php
$('select[name="employees"]').html(data);
}
}
</script>
Now I just freehanded that. But I'll try and walk you though it. First we grab the "select" tag that we want to watch (the hashtag means find the element by ID). Then we grab the selected option within that. Next we run a AJAX call to preform a GET on the page "DropdownRetrievalScript.php" which you would create. What that script should do is take the GET variable "option" and run it through the database. Then have it echo out the "option" tags. Our javascript stuff then takes those results and plugs them directly into the select tag with the name attribute of employees.
Remember that AJAX is just like inputing that url into your browser. So the data variable is literally whatever code or text that url would display. It can be Text, HTML, JSON, XML, anything.

Categories

Resources