I have been trying to figure out a way to populate second dropdown from database, based on user's selection in the first dropdown.
So far, CSS Tricks (Dynamic-Dropdowns) this is the best and most clear answer for my question. Although I am not able to make mine work. (There are 3 examples to populate dropdown, you should check the database one, which is on the bottom of the page.)
I have 2 dropdowns in my settings.php and as tutorial showed I created another php file to print out second dropdown.
This is get-dropdown.php:
<script>alert("Here")</script>
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$dbConnection = open_connection();
if(isset($_GET['School'])){ $school = mysqli_real_escape_string($dbConnection, $_GET['School']); }
/* This code will print program options from database.
*
* If user's program matches with any of the school from database,
* mark it as "selected" otherwise, use "Select Your Program" as selected.
*
* So, "selected" attribute of user's program will overwrite the "selected"
* attribute of "Select Your Program".
* */
$query_programs = "SELECT * FROM PROGRAMS WHERE PROGRAM_SCHOOL='$school' ORDER BY PROGRAM_CODE ASC";
$query_users = "SELECT USER_PROGRAM FROM USERS WHERE USER_ID = $user1_id";
$programs_result = mysqli_query($dbConnection, $query_programs) or die(mysqli_error($dbConnection));
$users_result = mysqli_query($dbConnection, $query_users) or die(mysqli_error($dbConnection));
while($data = mysqli_fetch_assoc($users_result)){ $user_program = $data['USER_PROGRAM']; }
foreach($programs_result as $program_result){
if($user_program == $program_result['PROGRAM_CODE']){
echo "<option value='$program_result[PROGRAM_CODE]' selected>$program_result[PROGRAM_CODE]</option>";
}else{
echo "<option value='$program_result[PROGRAM_CODE]'>$program_result[PROGRAM_CODE]</option>";
}
}
close_connection($dbConnection);
Even the alert on the top doesn't work. I putted there to see if it goes this page. When I selected another option from first dropdown, second dropdown gets empty. Nothing appears inside. Looks like I am making a mistake in settings.php because alert doesn't work on top.
This is some part of my settings.php:
<label>
<span>School:</span>
<select class="settings-input" name="school" id="school">
<option value="Select Your School" disabled selected>Select Your School</option>
<?php
/* This code will print school options from database.
*
* If user's school matches with any of the school from database,
* mark it as "selected" otherwise, use "Select Your School" as selected.
*
* So, "selected" attribute of user's school will overwrite the "selected"
* attribute of "Select Your School".
* */
$query_schools = "SELECT * FROM SCHOOLS ORDER BY SCHOOL_TYPE ASC";
$query_users = "SELECT USER_SCHOOL FROM USERS WHERE USER_ID = $user1_id";
$schools_result = mysqli_query($dbConnection, $query_schools);
$users_result = mysqli_query($dbConnection, $query_users);
while($data = mysqli_fetch_assoc($users_result)){ $user_school = $data['USER_SCHOOL']; }
foreach($schools_result as $school_result){
if($user_school == $school_result['SCHOOL_NAME']){
echo "<option value='$school_result[SCHOOL_NAME]' selected>$school_result[SCHOOL_NAME]</option>";
}else{
echo "<option value='$school_result[SCHOOL_NAME]'>$school_result[SCHOOL_NAME]</option>";
}
}
?>
<option value="Other">Other</option>
</select>
</label>
<label>
<span>Program:</span>
<select class="settings-input" name="program" id="program">
<option value="Select Your Program" disabled selected>Select Your Program</option>
<script>
$("#school").change(function(){
$("#program").load("./lib/get-dropdown.php?school=" + $("#school").val());
});
</script>
</select>
</label>
Thank you very much.
FINALLY FIXED (MY SOLUTION)
1. I have $dbConnection = open_connection(); to connect database but this function is defined in another file and the necessary information to connect database is stored in another file. So, to my get-dropdown.php I had to require both files. So this is how I fixed the db connection.
2. Other problem is I pass the school name to get-dropdown.php but the problem is school names contain spaces and this is a problem when you tried to pass in get. So this is what I used to pass get value. I added encodeURIComponent.
<script>
$(document).ready(function(){
$("#school").change(function(){
$("#program").load("lib/get-dropdown.php?School=" + encodeURIComponent($("#school").val()));
});
});
</script>
These were the problems. If you are trying to populate dropdown and no idea about javascript, this is the most easy way. With a little bit jquery, you can achieve it.
FINALLY FIXED (MY SOLUTION)
1. I have $dbConnection = open_connection(); to connect database but this function is defined in another file and the necessary information to connect database is stored in another file. So, to my get-dropdown.php I had to require both files. So this is how I fixed the db connection.
2. Other problem is I pass the school name to get-dropdown.php but the problem is school names contain spaces and this is a problem when you tried to pass in get. So this is what I used to pass get value. I added encodeURIComponent.
<script>
$(document).ready(function(){
$("#school").change(function(){
$("#program").load("lib/get-dropdown.php?School=" + encodeURIComponent($("#school").val()));
});
});
</script>
These were the problems. If you are trying to populate dropdown and no idea about javascript, this is the most easy way. With a little bit jquery, you can achieve it.
Related
I'm creating a cart page using PHP. I have managed to store the items that the person wants to buy in a session variable which stores an associative array that has the identifier of the item as the key and the quantity of the items as the value:
if (isset($_POST["btnSubmit"])){
$_SESSION["cart"][$isbn] += 1;
header("Location:cart.php");
}
I also managed to list these items on the cart using a foreach loop and a query:
<?php
$total;
foreach($_SESSION["cart"] as $product=>$quantity){
$query = mysqli_query($con,"SELECT * FROM BOOKS WHERE $product LIKE isbn");
$data = mysqli_fetch_array($query, MYSQLI_ASSOC);
$title = $data["title"];
$price = $data["price"];
$image = $data["image"];
$author = $data["author"];
$isbn = $data["isbn"];
print
"<a href='product.php?product=".$isbn."' class='list-group-item list-group-item-action>
<img src='".$image.">
<h5>".$title."</h5>
<h5>£".$price."</h5>
</a>
<select name='quant' id='quant'>
<option value=''>".$quantity."</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
</select>";
$total += $price*$quantity;
}
?>
As you can see, there is a dropdown list that I want to use to modify the number of items purchased. I need this list to update the value of the specific key within the $_SESSION['cart'] variable and then for that quantity to dynamically multiply by the price to display a total. For this, I am using jQuery.
<script>
$(document).ready(function(){
$("#quant").change(function(){
$.get('ajax/getTotal.php',{quant:$(this).val()},function(data){
$('#total').load(data);
});
});
});
</script>
I need to know two things:
How do I update the values in the SESSION variable without affecting the other values?
How do I properly use jQuery to dynamically update the total after the values in the SESSION variable have been updated?
I really appreciate your help. I'm really new to AJAX and I am very lost.
If I get you correctly, what you are trying is impossible. PHP is run on the servers building the HTML. After the page is served to the client/browser you cannot manipulate the PHP variable anymore.
You can manipulate the HTML using JS, e.g. to change the value of a DOM Element to show the total. However, this will be only effective on the client side. Using jQuery: https://www.w3schools.com/jquery/jquery_dom_set.asp
To make such a change effective on the server side / the session (which is also handled on the server) as well you will have to send a POST request to your server.
The easiest way for this is a to wrap your isbn and quantity into a normal <form method="POST" action="/pathToSessionUpdatingScript">.
E.g. using an <input> field for the isbn and <select> for the quantity. If you want to avoid clicking a button you can submit the form using JS / JQuery using the change event like you did above.
On the server side you then simply update the session using another php script
After that you may redirect to your original page.
Hope this helps!
I have a small project I'd like to get done concerning the use of a MySQL Database.
I want to create a two option dropdown menu. Each of these will contain a list of all the countries in the world, but based on the combination of options they select, they will be sent to a different page on our website.
Since the number of possibilities is going to be so large (200 x 200 countries = 40,000 potential answers) we decided it would be best to seed a MySQL database with all this information and then have simple code on our website which would pull them to the right place depending on the option they picked. Unfortunately none of us here have any experience with something like this, so we are looking for someone who can help us to:
1) Create the HTML and Javascript that will sit on our website
2) Establish the connection from the MySQL Database to our website to be able to pull in the values
3) Make the values selected point to the URLs we choose
Could anyone point me in the right direction as to how to do this?
Thanks!
You can use this code for the dependent dropdown. In fact, you don't need to do more simply on change event you need to get a value of selected drop-down and make an ajax call on the database in return data from your database on bases of that value then you can append data on success in another dropdown and can continue this process for more dependent dropdown.
<?php
require_once('db.php');
$country_result = $conn->query('select * from countries');
?>
<select name="country" id="countries-list">
<option value="">Select Country</option>
<?php
if ($country_result->num_rows > 0) {
// output data of each row
while($row = $country_result->fetch_assoc()) {
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["country_name"]; ?></option>
<?php
}
}
?>
</select>
</br></br></br>
<select name="state" id="states-list">
<option value=''>Select State</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
$('#countries-list').on('change', function(){
var country_id = this.value;
$.ajax({
type: "POST",
url: "get_states.php",
data:'country_id='+country_id,
success: function(result){
$("#states-list").html(result);
}
});
});
</script>
Code is below.... I have dropdown menu - that is using PHP to query SQL, in order to populate the dropdown menu options, which is working fine.
You will see below - the sql query is statically configured, I would like to make this more dynamic.
Ideally id like another drop down menu on the same page with statically configured country options, and then when the customer selects which country my PHP script updates with the country in the sql query that php is using....
So for example where in my script below it says;
WHERE country ='SE'
I want it to populate with which ever country the user has selected in the pull down menu, so it could be 'FR', 'DE' or whatever country code has been selected.
I suspect this may be javascript? or maybe php can do this...?
I'm very much a novice level - so if you can be of assistance as much detail, or script as possible please :)
<html>
<body>
<form name="search" action="\cgi-bin\eu.py" method="get">
<?php
require_once 'db.inc.php';
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$sqlSelect="SELECT * FROM clnts WHERE country ='SE' ORDER BY clnt_name";
$result = $mysqli -> query ($sqlSelect);
if(mysqli_num_rows($result)){
$select= '<select name="select">';
while($rs=mysqli_fetch_array($result)){
$select.='<option value="'.$rs['mgmt_ip'].'">'.$rs['clnt_name'].'</option>';
}
}
$select.='</select>';
echo $select;
?>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You can POST the selected dropdown value to the same page. You can do this automatically by using an 'onChange()' event on the dropdown menu.
Use this to POST to the same page and then get the value for the selected option and use that in your query...
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
add this at the top of you PHP....
if(isset($_POST['select']))
{
$selected_country_var = " country = '" . $_POST['select'] . "' ";
}else
{
$selected_country_var = " ";
}
edit your query to ...
$sqlSelect="SELECT * FROM clnts WHERE" . $selected_country_var . " ORDER BY clnt_name";
now edit your option/dropdown to have the onChnange event...
<select name="select" onchange="this.form.submit()">';
Let me know if I should clarify or if you need additional functionality.
It's usually not a "clean" solution to put together both server and client side code on the same page.
It's actually a better practice to put the server code on a seprate file for example 'handler.php' or 'api.php' and then call it using XMLHttpRequest (more commonly known as AJAX) ...
then, when using ajax you can pass data to the server using POST or GET variables and have it process the data.
that way you can create client side which is more fluent, and communication between the server and the client will be more "tidy"
in your case if you have say 'handler.php' on the server and use jquery ajax you could do something like :
client.html
$.ajax({
url : 'path_to_handler.php',
method : 'POST',
data : { countryCode : 'IL', otherVar : 1 },
onSuccess : function(result){
// do whatever with the data
}
});
and on the server
handler.php
if( isset($_POST['contryCode']) ){
// query the db and have the result returned as json
echo json_encode($result_query);
}
I'm a total noob when it comes to jQuery. This time I would like to populate a select box when a user clicks it. I managed to do that, but each time the user selects an option the select box instantly changes it's value back to default, so the user can't select the one he wants. Below you can view the code from Joomla that loads the database and the HTML file with the select box. I know I'm doing something wrong but I'm not sure what this is...
widget.php - Joomla Database file with query
<?php
// Set flag that this is a parent file.
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
if (file_exists(dirname(__FILE__) . '/defines.php')) {
include_once dirname(__FILE__) . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', dirname(__FILE__));
require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
$db = JFactory::getDbo();
$db2 = JFactory::getDbo();
$sql = "SELECT id, type, name FROM #__widgetkit_widget WHERE type = 'gallery'";
$db->setQuery($sql);
$rows = $db->loadObjectList();
$query = "SELECT id, b_name, w_id FROM #__yachts WHERE id = ".JRequest::getInt('id')."";
$db2->setQuery($query);
$rows2 = $db2->loadObjectList();
$my_yacht = $rows2[0]->w_id;
echo '<option value="">-- Please Select --</option>';
foreach($rows as $row) {
echo '<option value="'.$row->id.'"';
if($row->id == $my_yacht) { echo ' selected'; }
echo '>'.$row->name.'</option>'."\n";
}
?>
And the HTML file with the JavaScript:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html prefix="og: http://ogp.me/ns#" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" dir="ltr" >
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var j = jQuery.noConflict();
j(document).ready(function () {
j("#jform_w_id").click(function () {
j("#jform_w_id").load('widget.php');
});
});
</script>
</head>
<body>
<select class="" id="jform_w_id" name="jform[w_id]">
<option value="">-- Please Select --</option>
<option value="59">Bavaria 50 Cruiser</option>
<option value="60">Bavaria 49</option>
</select>
</body>
</html>
The problem is that you're reloading the select box from widget.php every time a user clicks on the #jform_w_id select box. Since you aren't first grabbing the previously selected item, the previous selection is lost.
One solution is to store off the previously selected value before loading, then reassign the selection after loading, like so:
<script type="text/javascript">
var j = jQuery.noConflict();
j(document).ready(function () {
var selectBox = j('#jform_w_id');
selectBox.click(function () {
var oldValue = selectBox.val();
selectBox.load('widget.php');
selectBox.val(oldValue);
});
});
</script>
With that said, I'm not convinced this is a good pattern, for a few reasons:
1) You're reloading from the server every time the user clicks that select. If the list is long, you're going to have a noticeable lag between the time the user clicks and the time the select box pops up. Make sure you understand why you are loading the data from the server every time there's a click, and make sure your use case really requires that. You may be able to have a process that caches the values and repopulates the dropdown asynchronously.
2) I haven't tested this, but it's possible that reloading the options box after clicking could cause the control to flicker, lose focus, or other unexpected behavior.
3) If you need to support mobile users, the above issues will be exacerbated by UI and bandwidth constraints.
Since I don't know your particular use case, these may be concerns you've already thought of, but if not, please consider them as you craft your page.
Finally, please consider replacing this line
$query = "SELECT id, b_name, w_id FROM #__yachts WHERE id = ".JRequest::getInt('id')."";
with a prepared statement. While the fact that you're currently parsing an int from the request object protects you from SQL injection attacks for this one use case, you'll glad you used prepared statements if you copy this chunk of code for use elsewhere where the WHERE clause parameter is a string. The semantics of prepared statements will depend on the DB you're using and Joomla's database API, but it's usually something like:
$query = "SELECT id, b_name, w_id FROM #__yachts WHERE id = :id";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':id', JRequest::getInt('id'));
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
...
}
}
See: http://us1.php.net/pdo.prepared-statements
I have two dropdown menus that read their data from a MySQL database. I use PHP for connecting to database. The second dropdowns should get populated based on the selection on the first dropdown. The process seems as below to me (correct me if I'm wrong):
PHP section connects to MySQL database and populates dropdown1.
user selects a value on dropdown1 and onchange event is called.
within the onchange function (which is Javascript), a query is sent to MySQL database to fetch values of dropdown2 based on the dropdown1 selection (here is PHP again, right?).
dropdown2 gets populated.
I don't know how to use Javascript and PHP together in order to do this task (number 3 above); or maybe this is not the way to do it at all. Please advise!
Here is my code. As you see below, I'm putting a Javascript function within a PHP code which I suppose is wrong. That's where I got stuck!
<php
$sql="SELECT distinct category FROM table1";
$result=mysql_query($sql);
$optionsCat="";
while($row = mysql_fetch_row($result)){
$optionsCat.="<option value=\"$row[0]\">$row[0]</option>";
}
function genSubCat($catID){
$sql="SELECT distinct subcategory FROM table1 where category=".$catID;
$result=mysql_query($sql);
$optionsSubCat="";
while($row = mysql_fetch_row($result)){
$optionsSubCat.="<option value=\"$row[0]\">$row[0]</option>";
}
}
?>
<select name="catDropDown" onChange="genSubCat(this)">
<option value="0">Select category</option>
<?php echo $optionsCat?>
</select>
<select name="subcategoryDropDown">
<option value="0">Select subcategory</option>
<?php echo $optionsSubCat?>
</select>
Here we have a simple page with input on it. Type a word into it and then click off of the input. Ajax will call the myphp.php script and return the same word you typed in below the original division.
test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#faq_search_input").blur(function(){
var faq_search_input = $(this).val();
var dataString = 'keyword='+ faq_search_input;
if(faq_search_input.length>1){
$.ajax({type: "GET", url: "myphp.php", data: dataString,
success: function(server_response) {
document.getElementById("searchresultdata").style.display = "block";
$('#searchresultdata').html(server_response).show();
}
});
}
return false;
});
});
</script>
</head>
<body>
<div class="searchholder">
<input name="query" class="quicksearch" type="text" id="faq_search_input" />
<div id="searchresultdata" class="searchresults" style="display:none;"> </div>
</div>
</body>
</html>
myphp.php:
<?PHP
echo $_GET['keyword'];
?>
I think you should first study yourself about using web based languages. The code that you've provided is completely wrong. You're trying to access PHP code through HTML? I mean come on!
First rule: Server based languages can't communicate with Client based languages.
You have to send requests and get responses and the way you want to do that dropdown thing is to send a request to a PHP code and get relevant data from it. As Trufa said in the comment, you may want to look at jQuery library, but before that I think you need to check AJAX.