Creating 3 option dynamic dependant dropdown list - javascript

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>

Related

Need to dynamically update a value in a PHP associative array using AJAX without updating other values

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!

Dynamic populating the drop down list based on the button clicked

I am working on a small project where I am trying to change the drop down list option based on the button that is clicked.
Its sort of like populating the list based on the value of the first list that I is listed here https://www.plus2net.com/php_tutorial/php_drop_down_list.php
However currently I have my select list displayed using php and html. I make a call to my table in the tags above my page and then display the information.
<?php
$selList = array();
$query= $dbh->query("SELECT * from CarsShop order by dtDroppedOff");
foreach ( $query->fetchAll(PDO::FETCH_ASSOC) as $row ) {
$selList [] = array('carID'=> $row['carID'], 'vin'=> $row['CarVIN']);
}
?>
<select name="carLst" id="carLst" onClick="retrieveCarInfo(this.getSelected().getProperty('value'));" size="5" >
<option>List of cars...</option>
<?php foreach ($selList as $entry) { ?>
<option value="<?php echo $entry['carID']; ?>"><?php echo $entry['vin']; ?></option>
<?php }?>
</select>
However I want to add two buttons..one to display all cars that are ready for pickup and those who are not. I have a simple 1 or 0 in my table and I can pull information like that. However how could I toggle back and forth when clicking the buttons. My select list would have to populate each time i click the corresponding button.
Now I am aware I can make a JSON call as an onclick() and request this information and assign it on the onSuccess callback, but is there any way of doing this like how I already have it?

Dynamic Select Field that Repopulates after Changes in Another Select Field - Laravel 5.2 and JS

I am developing a web app using Laravel 5 and trying to integrate some JS to help out a form. I want users to be able to select a category in one select field, at which point a second select field should populate with options within that category. (E.g., Select a profession: programmer, artist. If 'programmer' is selected, second select field populates with: C++, Java, Python. If 'artist' is selected, second select populates with: Photoshop, Illustrator, MS Paint.)
Note that I need to populate these fields from my database. I've found examples of what I am trying to do on the web that I have tried to adapt to my case. The one I'm using is here: http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html but I can't get it to work (it's fairly old--from 2010).
Here's my HTML and JS:
<!-- JS -->
<script type="text/javascript">
$(document).ready(function()
{
$("#field_main").change(function()
{
var id = $(this).val();
var fields="";
$.ajax
({
type: "POST",
url: "ajax_field.php",
data: {id: id},
cache: false,
success: function(data)
{
$.each(data,function(index,field)
{
fields+="<option value='"+field.id+"'>"+field.field+"</option>";
});
$("#field").html(fields);
}
});
});
});
</script>
<!-- Create the first select field, this part of the code works fine -->
<label>Area :</label>
<select name="field_main" id="field_main">
<option selected="selected">--Select Area--</option>
<?php
$areas = App\Area::all();
foreach($areas as $area){
echo "<option value=\"" . $area->id . "\">" . $area->area . "</option>";
}
?>
</select>
<!-- Create the second select field; this part is not working -->
<label>Field :</label>
<select name="field" id="field">
<!--<option selected="selected">--Select Field--</option>-->
</select>
Here's what ajax_field.php looks like:
<?php
namespace App\Http\Controllers;
use DB;
if($_POST['id'])
{
$id = $_POST['id'];
$fields = DB::table('fields')->where('area_ref', $id)->get();
return response()->json(['data' => ['fields' => $fields]]);
}
?>
As far as I can tell, nothing runs from ajax_skill.php. I tried echoing something out in that function, it didn't appear on my page, and the skills field never populates. The profession select field, however, populates fine.
Any thoughts on where this code is going wrong?
You need to return JSON when hitting that URL with AJAX. You don't need the HTML. Return only the skills data with return response()->json(['data' => ['skills' => $skills]]); and add the select element on the page populated with all of the skills.
Oh and, the ajax data property takes an object so it should be: data: {id: id}
Since you are using Laravel, half of your code looks like old school PHP which is useless when Laravel has a cleaner way for these things.
If you are new to PHP and Object Oriented Programming, I'd advice you to learn that before using Laravel. It will help you in the future.
Also, I'd advice you to read up the Laravel documentation, follow the tutorials there and even go to Laracasts and watch the Laravel 5 Fundamentals and Laravel From Scratch series to get up to speed with Laravel.

Making dynamic-dropdowns using database

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.

Dropdown onchange method using PHP and Javascript

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.

Categories