3 dependent drop down by Ajax and PHP - javascript

Good day ,
I have 3 PHP pages ('test1.php' , 'res.php' , 'desc.php') ,So I want to make 3 dependent drop down. all drop down dependent to previous drop down. So when I select an item from first drop down , all data fetch from database by 'res.php' and add to second drop down as item . But when I select second drop down , page will refresh and back to first step and all drop down item selected gone .
test1.php
<script>
function load_sub_cat(str){
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("get","res.php?q="+str,false);
xmlhttp.send();
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
</script>
<select name="users" onChange="load_sub_cat(this.value)">
<option value="0">Select a restaurant</option>
<?php
$db->setQuery("SELECT id, name FROM yh5lw_rest_dropdown where active=1");
$results = $db->loadObjectList();
foreach ($results as $result) {
echo "<option value=".$result->id.">". $result->name."</option>";
}
?>
</select>
<div id="txtHint"></div>
res.php
<script>
function load_sub_cat(str){
var xmlhttp1;
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("get","desc.php?desc="+str,false);
xmlhttp1.send();
document.getElementById("txt23").innerHTML=xmlhttp1.responseText;
}
</script>
<select name="users1" onChange="load_sub_cat(this.value)">
<option value="">Select a main course</option>
<?php
$q = intval($_GET['q']);
$db->setQuery("SELECT price,id, nameEN , nameFA FROM yh5lw_food_dropdown where active=1 AND res_id ='".$q."'");
$results = $db->loadObjectList();
foreach ($results as $result) {
echo "<option value=".$result->id.">". $result->nameEN." (".$result->price"</option>";
}
$count++ ;
}
?>
</select>
<div id="txt23"></div>
desc.php
<?php echo $_GET['desc'] ?>

Although you can write your own code for this, you don't need to reinvent the wheel for this functionality - try the jQuery Cascading Dropdown Plugin, it's free and does precisely what you want to do. It's easy to setup, it supports AJAX, and and you'll only need to use your server-side code for the AJAX calls.

Related

How can get the refreshed option values from database only when i click on select box?

I want to get the refreshed option values from database only when i click on select box.
Suppose two waiter open the same order panel page at same time. Then table no:2 is shown as free in both of the panel.
Now a waiter booked table no:2. Then another waiter when clicked on the select box, he will not get the table no:2 in the options.
<select name="table_id" class="form-control tablename">
<option disabled="disabled">Select Table</option>
<?php $result = mysql_query("select * from rtable r
inner join table_status as ts
on ts.status_id=r.status_id
where ts.status!='Booked'
order by r.table_id desc")or die(mysql_error());
while ($row=mysql_fetch_array($result)){ ?>
<option value="<?php echo $row['table_id'];?>"><?php echo $row['table_name']; ?></option>
<?php } ?>
</select>
table_status
rtable
Create function in php to generate options ( sending html is not good practice but I am adjusting to this example). In this particular example i suggest to create functions.php file and there add printSelectOptions function declaration:
function printSelectOptions(){
$result = mysql_query("select * from rtable r
inner join table_status as ts
on ts.status_id=r.status_id
where ts.status!='Booked'
order by r.table_id desc")or die(mysql_error());
echo "<option disabled='disabled'>Select Table</option>";
while ($row=mysql_fetch_array($result)){
echo "<option value=".$row['table_id'].">".$row['table_name']."</option>";
}
}
Above function prints all html options for select.
Use it function in generating select ( remember that functions.php should be included in any file with usage of printSelectOptions ):
<?php
//db connection code
require_once("functions.php");//here we add our function to be available in this file
?>
<select name="table_id" class="form-control tablename">
<?php printSelectOptions() ?>
</select>
In frontend bind Your select ( javascript code ):
document.addEventListener("DOMContentLoaded", function(event) {
var select=document.querySelector("select"); //this is pure selector gets first select on page
//function sends ajax and refresh options of select
function refreshOptions(){
//send ajax request
select.innerHTML="<option>Loading..</option>"; //loading info
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", 'yourSecondPHPScript.php');//here example url where we get updated options
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if(xmlhttp.status == 200){
select.innerHTML = xmlhttp.responseText;//set new options
}else{
console.log('Error: ' + xmlhttp.statusText )
select.innerHTML="<option>Connection problem</option>";
}
}
}
xmlhttp.send();
};
//bind our select
select.addEventListener("focus",function(){
refreshOptions();
});
});
Last create example yourSecondPHPScript.php and in it use function:
<?php
//db connection code
require_once("functions.php");//here we add our function to be available in this file
printSelectOptions();//outputs options
To be sure that users will not take the same table besides checking in focus check it again in some submit of order form. So if table was taken refresh select ( by ajax using refreshOptions() ) and show info that this table was taken.
Last thing is to secure it on server side, create some check function in php ( PHP CODE ):
function tableCanBeTaken($optionId){
//this code adds **and** to query with id to check but optionId should be validate before using in query
$result = mysql_query("select * from rtable r
inner join table_status as ts
on ts.status_id=r.status_id
where ts.status!='Booked'
and ts.table_id=$optionId ")or die(mysql_error());
return mysql_fetch_array($result); //if row exists - will be false if not exists row with table_id==$optionId and not booked
}
}
Then use it (PHP CODE ):
if (tableCanBeTaken($youOptionId)){
//here code for taking option
}else{
//here option is taken
}
Have the ajax call in the focus event of the select box.In the success of the call, append the data(available tables) to the select input.Until then, leave the select box options as 'Loading. Hope this helps!
#Maciej Sikora
problem is fixed. printSelectOptions() function can not be called from another file like yourSecondPHPScript.
And also needs to remove the back-slash from url.
xmlhttp.open("GET", 'yourSecondPHPScript.php');
i just paste the same code in yourSecondPHPScript.php like below
<?php
include("connect.php");
$result = mysql_query("select * from rtable r inner join table_status as ts on ts.status_id=r.status_id where ts.status!='Booked' order by r.table_id desc")or die(mysql_error());
echo "<option disabled='disabled'>Select Table</option>";
while ($row=mysql_fetch_array($result))
{
echo "<option value=".$row['table_id'].">".$row['table_name']."</option>";
}
?>

Populate a dropdownlist after selecting a value from a different list using Ajax

I have 2 dropdownlists. The first contains Car Brands like seat,bmw,audi etc.
The second i want to contain the models from the specific Brand the user selected in list 1.
In my current code state, when i select A brand from List 1 the second list is getting Filled with the same elements from List 1. So I Have a Duplicated List with exactly the same records.
The main file:
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
$css='css.css';
$doc = JFactory::getDocument();
$doc->addStyleSheet('modules/mod_alpha_table/assets/'.$css);
$db= JFactory::getDbo();
$ready = $db->getQuery(true);
$query="SELECT category_name,virtuemart_category_id from uhhu_virtuemart_categories_el_gr INNER JOIN uhhu_virtuemart_category_categories ON uhhu_virtuemart_categories_el_gr.virtuemart_category_id = uhhu_virtuemart_category_categories.category_child_id WHERE uhhu_virtuemart_category_categories.category_parent_id = 105";
$db->setQuery($query);
$options=$db->loadObjectList();
$model="";
?>
<script>
function showUser(str) {
var xmlhttp;
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","query.php?q="+str,true);
xmlhttp.send();
}
</script>
<div class="srchcr">
<div class="srch">
<form name="searchcar">
<form>
<select onchange="showUser(this.value)" name="cats">
<option value="none">Select Make</option>
<?php foreach ($options as $row) {
echo '<option value=' . $row->virtuemart_category_id . '>'. $row->category_name . '</option>';
}
?>
</select>
<select name="subcats" id="txtHint">
<option value="none">Select Model</option>
</select>
</form>
</div>
</div>
query.php file :
<?php
$doc = JFactory::getDocument();
$db= JFactory::getDbo();
$ready = $db->getQuery(true);
$q = htmlspecialchars($_REQUEST['q']);
$query='SELECT category_name,virtuemart_category_id from #__virtuemart_categories_el_gr INNER JOIN #__virtuemart_category_categories ON #__virtuemart_categories_el_gr.virtuemart_category_id = #__virtuemart_category_categories.category_child_id WHERE #__virtuemart_category_categories.category_parent_id = $q';
$db->setQuery($query);
$options=$db->loadObjectList();
foreach ($options as $row) {
echo '<option name='. $q .' value=' . $row->virtuemart_category_id . '>'. $row->category_name . '</option>';
}
?>
Query tested at phpmyAdmin and working fine. It seems somehow the first query is getting executed twice instead of the query inside the $query.php file. I also tried include the code from the external file inside the main but its the same story.I also renamed the second $query as $query2 and executed $query2 but nothing changed.Could someone enlight me on what is going wrong ?
EDIT:
After a break and bit more debugging i think that this is where the problem start:
xmlhttp.open("GET","query.php?q="+str,true);
It seems like the request for some reason, instead of query.php is sent at index.php and triggers the same query again.I added die(); at the start of query.php and nothing happened.So may i need to use a joomla syntax or something ?
Looks like you have a copy-paste-error here. When comparing the creation of your option-tags, I see the exact same code for both the brands and the models, meaning query and dom-creation.
So basically, your code is perfectly fine. But in your query.php you are creating this same brand-list again ;)
Some general comments on your code:
Do not create your own implementation of the XmlHttpRequest, use a library like jquery or mootools
You are vulnerable to sql-injections when using values from userland ($_REQUEST['q']) without sanitizing them. See this question on stackoverflow: Best way to prevent SQL injections in Joomla
if it is true that you gather the information for your 2 lists with the same query, try to implement your logic (user selects brand, model-list is updated) through javascript. So your main.php still creates the brand-list, but renders all model-lists as well. These are shown/hidden when the user changes the brand accordingly. This would avoid the additional roundtrip to the server each time a brand is selected.

how to get values from mysqldb to dropdownbox using php ajax?

how to get values from mysql db to dropdownbox using php ajax?
what i need is
when i select anyone value from dropdownbox then the corresponding row values(get from db) will be displayed to another dropdownboxes/textboxes?
Thanks
Siva
you will have to use both javascript and php to achieve this
<select id="month" onchange="change()">
<option value="1">January</option value="2">
<option value="1">January</option value="2">
</select>
<div id="result"></div>
<script>
function change(){
var sel_month = $('#month').val();
$.post("url_to_your_php_file", {month:sel_month})
.done(function(data) {
$('#result').html(data);
});
}
on php side...
<?php
$month = $_POST['month'];
//run your query here
//result should be an array...
//populate a select box with the array...
echo '<select>';
foreach($result as $data){
echo '<option value="'.$data['id'].'">'.$data['name/title'].'</option>';
}
echo '</select>';
Suppose this is my select drop down , i want to display data corresponding to a month ,
Is that your question ?
<select name="monthview" onchange="showUser(this.value)">
<option><b>Change Month</b>
<option value="1">January
<option value="2">February
<option value="3">March
<option value="4">April
<option value="5">May
<option value="6">June
<option value="7">July
<option value="8">August
<option value="9">September
<option value="10">October
<option value="11">November
<option value="12">December
</select></td>
<div id="txtHint">YOUR NEW DROP DOWN WITH ROWS FROM DB WILL BE HERE </div >
*** AJAX CALL ***:
<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;
}
}
var x=document.myForm.eid.value;
xmlhttp.open("GET","databasefetch.php?q="+str,true);
xmlhttp.send();
}
</script>
PHP SIDE YOU NEED TO RECEIVE THE MONTH VALUE AND THEN SEND IN THE CORRESPONDING ROWS IN A DROP DOWN AS A RESPONSE TO AJAX CALL , LIKE THIS .
$month_selected = $_GET['q'];
//connect to database
$result ="your sql query"
//create a drop down now
echo "<select>";
echo "<select name='projectassignedto'>";
echo "<option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['employeeid'] ."'>" . $row['employeeid'] ."</option>";
}
echo "</select>";
echo "";
u can goto w3 and get the code for php-ajax-sql , Your work shall be done if you have little knowledge with php and sql .

how manage auto-submit with the action atribute in the form

I needed make a dinamic dependent dropdown in a form,so i found this solution that uses the JS auto-submit function:
function autoSubmit()
{
var formObject = document.forms['dados'];
formObject.submit();
}
then I use the onchange event in the first dropdown to call the auto-submit function:
<label>Campus:</label>
<select name="campus" onchange="autoSubmit();">
<option VALUE="null"></option>
<?php
//Popula a lista com os cursos do DB
$sql = "SELECT id,nome FROM campus";
$countries = mysql_query($sql,$conn);
while($row = mysql_fetch_array($countries))
{
if($row[nome]==$campus)
echo ("<option VALUE=\"$row[nome]\" selected>$row[nome]</option>");
else
echo ("<option VALUE=\"$row[nome]\">$row[nome]</option>");
}
?>
</select>
with this the element "campus" will be setted to be used in the second dropdown SELECT statement:
$campus = $_POST['campus'];
...
<label>Curso:
<span class="small">curso corrente</span>
</label>
<select name="curso">
<option VALUE="null"></option>
<?php
$consulta2 = "SELECT curso FROM campus_cursos WHERE campus = \"" . $campus . "\"";
$cursoslista = mysql_query($consulta2,$conn);
while($row = mysql_fetch_array($cursoslista))
{
echo ("<option VALUE=\"$row[curso]\">$row[curso]</option>");
}
?>
</select>
this code is working,but the problem is that in this way I cant set a action atribute in the form because if i do this every time the first dropdown changes it will redirect to the action's URL.this is the form that works:
<form name="dados" method="POST" onsubmit="return validar();">
with no action atribute I cant use a submit button to send the data of all the others elements to the right URL.there is a way to this?
You should use Ajax code to populate the second dropdown values.
On Form's page:
<label>Campus:</label>
<select name="campus" id="campus">
<option VALUE="null"></option>
<?php
//Popula a lista com os cursos do DB
$sql = "SELECT id,nome FROM campus";
$countries = mysql_query($sql,$conn);
while($row = mysql_fetch_array($countries))
{
if($row[nome]==$campus)
echo ("<option VALUE=\"$row[nome]\" selected>$row[nome]</option>");
else
echo ("<option VALUE=\"$row[nome]\">$row[nome]</option>");
}
?>
</select>
<label>Curso:
<span class="small">curso corrente</span>
</label>
<select name="curso" id="curso">
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#campus').change(function(){
var campusName = $(this).val();
$('#curso').load('generateCurso.php?campus='+campusName);
});
});
</script>
Write a PHP file, called generateCurso.php
<?php
$campus = $_GET['campus'];
$consulta2 = "SELECT curso FROM campus_cursos WHERE campus = \"" . $campus . "\"";
$cursoslista = mysql_query($consulta2,$conn);
?>
<option VALUE="null"></option>
<?php
while($row = mysql_fetch_array($cursoslista))
{
echo ("<option VALUE=\"$row[curso]\">$row[curso]</option>");
}
?>
I solved this issue using a ajax script triggered by "on change" event.the ajax script call a external file that return an array of elements.the script use these elements to populate the dropdown list.

dropdown list not populating with Ajax

Whilst I'm sure it must be something really obvious, I can't see where I am going wrong with this. I have a drop down list with two options in it. When I Select an option it should use XMLHttpRequest() to get a list of customers from the database, based on the option selected.
I have two parts:
ajax2_js.php - contains the javascript and html form.
ajax2_DBAccess.php - contains the PHP that gets the list from the databse.
I have checked everything on the second page, and this works fine on it's own (and displays the relevant list as a dropdown menu), but when I select the option on the first page, nothing happens.
My code thus far is:
ajax2_js.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script>
function ajaxFunction()
{
var ajaxRequest;
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
document.getElementById('customerDiv').innerHTML=req.responseText;
}
}
ajaxResuest.open("GET", strURL, true);
ajaxRequest.send(null);
}
</script>
</head>
<body>
<form method="post" action="" name="form1">
Network : <select name="network" onChange="ajaxFunction('ajax2_DBAccess.php?network='+this.value)">
<option value="">Select Network</option>
<option value="1">Net1</option>
<option value="2">Net2</option>
</select>
</br>
Customer : <div id="customerDiv">
<select name="select">
<option>Select Customer</option>
</select>
</div>
</form>
</body>
ajax2_DBAccess.php
<?php
$network=$_GET['network'];
$q1 = "SELECT `CustName` FROM monitor.customers where network = $network;";
$con = new mysqli('localhost:3306', 'xxx', 'xxx');
if (mysqli_connect_errno())
{
$error = mysqli_connect_error();
echo $error;
exit();
}
else
{
$ConfRes = mysqli_query($con, $q1);
if ($ConfRes)
{
echo "<select name=\"Customers\">";
echo "<option>Select Customer</option>";
while($row=mysqli_fetch_array($ConfRes, MYSQLI_ASSOC))
{
$result = $row['CustName'];
echo "<option value>$result</option>";
};
echo "</select>";
}
else
{
$error = mysqli_error();
echo $error;
exit();
}
};
?>
Any assistance would be appreciated.
Check the javascript error log.
This might be the problem, a spelling error in "Request".
ajaxResuest.open("GET", strURL, true);
Also, your SQL query suffers from an SQL injection vulnerability in the $network parameter.
You can either use XML or JSON to return list. This tutorial should help. I personally would use XML.
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("CustName",$row['CustName']);
}
echo $dom->saveXML();
but there are plenty of tutorials on both methods.
Thanks for all your help guys, I have tracked it down to three things (all my fault):
function ajaxFunction()
should be:
function ajaxFunction(strURL)
.
ajaxResuest.open("GET", strURL, true);
should be:
ajaxRequest.open("GET", strURL, true);
.
and finally:
document.getElementById('customerDiv').innerHTML=req.responseText;
should be
document.getElementById('customerDiv').innerHTML=ajaxRequest.responseText;
.
(and of course the SQL injection vulnerability mentioned above which I will also fix).
cheers.

Categories

Resources