Get text from dynamic dropdown and use it in another file - php

On my web page I have two dropdown menus. One for a list of countries and another for a list of city's. The country menu is populated with data from a database. Once one of these countries are selected, the following dropdown is populated with corresponding cities via a php file (getdata.php) which takes the country value selected and queries it with a database and echos the city names into the dropdown. What I am struggling to work out is, when a city is selected, how would I get the text of the city selection and use this text in another php (displayCity.php) to query the database and echo values such as Population into the textbox (without reloading page) back on the web page? Would I need to make the displayCity.php similar to the getData.php? I have already created a new Ajax method for the textbox but I am not sure if I will need this. Advice would be greatly appreciated.
<?php include_once "connection.php"; ?>
<!DOCTYPE html>
<html>
<head>
<title>City displayer</title>
<h1>City displayer</h1>
<link rel="stylesheet" type="text/css" href="homepagestyle.css">
</head>
<body>
<div class = "country">
<label>Select Country: </label>
<select name="country" onchange="getId(this.value);">
<option value = "">Select Country</option>
<?php
$query = "SELECT DISTINCT(Country) from location AS Country FROM location ORDER BY Country ASC;";
$results = mysqli_query($con, $query);
foreach ($results as $country) {
?>
<option value = "<?php echo $country['Country']; ?>"><?php echo $country['Country'] ?></option>
<?php
}
?>
</select>
</div>
</br>
</br>
<div class="city">
<label>Select a City: </label>
<select name="city" id="cityList" onchange="showCity(this.value)">
<option value="">Select a city</option>
</select>
</div>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
function getId(value){
$.ajax({
type: "POST",
url: "getdata.php",
data: "Country="+value,
success: function(data){
$("#cityList").html(data);
}
});
}
</script>
</br>
<div id = "textbox">Choose a country and city to display city name here</div>
<script>
function showCity(value){
$.ajax({
type: "POST",
url: "displayCity.php",
data: "City="+value,
success: function(data){
$("#textbox").html(data);
}
});
}
</script>
</body>
</html>
getdata.php
<?php
include_once "connection.php";
if(!empty($_POST['Country'])){
$country = $_POST['Country'];
$query = "SELECT * FROM location WHERE Country= '$country'";
$results = mysqli_query($con, $query);
foreach ($results as $city) {
?>
<option value = "<?php echo $city['Country']; ?>"><?php echo
$city['City'] ?></option>
<?php
}
}
?>

Use AJAX along with a $_SESSION variable. No need to write it to the database. You just have to make sure you use session_start() everywhere you need it.

Related

How to sort a table contents according to values given in a select box in php?

I have a table containing some fields like name,address,item status in a table. I have values like Item Picked, Item Not Picked.
I have a select box like given below :
<select name="option" class="optionn">
<option value="">All</option>
<option value="itempicked">Item Picked</option>
<option value="itemnotpicked">Item Not Picked</option>
</select>
I want to sort the table contents according to the selected value in the select box.
How to do this ? Can anyone say how to do this ?
<select name="option" class="optionn" id="items">
<option value="">All</option>
<option value="itempicked">Item Picked</option>
<option value="itemnotpicked">Item Not Picked</option>
</select>
$.ajax({
url : 'example.php',
data:{
item:$('#items').val()
},
type: 'POST',
success: function(result){
console.log(result); // result set in table
}
})
in example.php file write query to get sorting data
Ex. $query = "SELECT * FROM items WHERE items = ".$_POST['item'];
This is just the example it's not your answer i hope it's help you.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="wrapper">
<div>
<select class="options" name="">
<option value="1">item_1</option>
<option value="1">item_2</option>
<option value="1">item_3</option>
</select>
</div>
</div>
<button type="button" class="addme" name="button">Add More</button>
</body>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$('.addme').click(function(){
$.ajax({
url:'getData.php',
type:'GET',
success:function(result){
console.log(result);
}
})
});
});
getData.php File
$query = "select * from items";
$row = mysql_query($query);
echo "<select>";
while($data = mysql_fetch_array($row)){
echo "<option>".$data['item_name']."</option>";
}
echo "</select>";

Building a dropdown based on another dropdown in php

New in php and ajax, building a dropdown based on another dropdown through database.Up to now code is sucessfully running, you can check my code having two php pages, dropdown2.php and postbrand.php now just want to know how to use $brand variable value in postbrand.php to use in the sql query in second dropdown in dropdown2.php.
<?php
require 'connect.inc.php';
$query = "SELECT * FROM `brand` ";
$data = mysql_query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Input form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12/jquery.min.js"></script>
</head>
<body>
<form>
<label>Brand:</label>
<select name="brand" id="sb" onchange="myFunction()">
<?php
while($row=mysql_fetch_array($data))
{
?>
<option value="<?php echo $row['b_name'];?>">
<?php
echo $row['b_name'];
?>
</option>
<?php
}
?>
</select>
<br/><br/>
<label>Model:</label>
<?php
$query = "SELECT model.model, model.b_id from model inner join brand on model.b_id= brand.b_id where brand.b_name like 'sony'";
$result = mysql_query($query);
$select= '<select name="select" id="sm">';
while($rs=mysql_fetch_array($result)){ $select.='<option value="'.$rs['b_id'].'">'.$rs['model'].'</option>';
}
$select.='</select>';
echo $select;
?>
</form>
<div id="result"></div>
<script>
function myFunction() {
//alert('working!!');
var brand = $('#sb').val();
$.post('postbrand.php', {postbrand:brand},
function(data){
$('#result').html(data);
});
}
</script>
</body>
</html>
postbrand.php
<?php
$brand = $_POST['postbrand'];
echo $brand;
?>
If I get it correct you want to populate the second dropdown based on the chosen value of the first dropdown.
To steps to achieve this are:
listen to "change" event on the first dropdown (using JQ)
var selected = ""
$('select#sb').on('change', function() {
selected = $(this).val(); // get the chosen value
});
$.post("postbrand.php", selected, function(resp){ //send the selected value to postbrand.php which will return an array of elements from db based on what was selected
$.each(resp,function(key, val){ //traverse the response and
$('select#secondDropdown').append('<option>'+val+'</option>') //populate the 2nd dropdown
})
})

Dynamic Dependant Dropdown menu with ajax php mysql

I am attempting to make dynamic dropdown boxes a search tool to help narrow down display data from a mysql server. I am a decent php programmer but need help with the javascript and ajax.
The site currently consists of 3 pages: index_test.php, dropdown.php and dropdown2.php.
On index_test.php there are 4 dropdown menus that need to be populated with information. The first is populated with state names from a mysql table using php when the page loads. The second box is populated using .change() that references php code and and displays schools in the selected state from a mysql table.
The third box is supposed to then take the selected value from the second box and display the class names from the selected school to the user and that step is where the code is breaking. The php works when tested by submitting the form but I would like to be able to fill the last 2 boxes without a page refresh.
The format of the mysql tables are:
table schools: (school_id, schools, states)
table classes: (class_id, school_id, class_abrv, class_number)
Thank you for your help
The code for index_test.php:
<?php include_once("connect.php"); ?>
<html>
<head>
<title>ajax</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#state").change(function(){
var state = $("#state").val();
$.ajax({
type:"post",
url:"dropdown.php",
data:"state="+state,
success: function(data) {
$("#school").html(data);
}
});
});
$("#school").change(function(){
var state = $("#school").val();
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+school,
success: function(data) {
$("#classname").html(data);
}
});
});
});
</script>
</head>
<body>
<h1>Get Notes:</h1>
<br/>
<form action="dropdown2.php" method="post">
State: <select id="state" name="state">
<option>--Select State--</option>
<?php
$sql = "SELECT states FROM states";
$result = mysql_query($sql);
while ($output = mysql_fetch_array($result)) {
$state_name = $output['states'];
echo "<option value=\"$state_name\">$state_name</option>";
}
?>
</select>
<br/>
School: <select id="school" name="school">
<option>--Select School--</option>
</select>
<br/>
Class Name: <select id="classname" name="classname">
<option>--Select Class Name--</option>
</select>
<br/>
Class Number: <select id="classnumber" name="classnumber">
<option>Select Class Name</option>
</select>
<br/>
<input type="submit" value="Search" />
</form>
</body>
</html>
Dropdown.php:
<?php
include_once("connect.php");
$state=$_POST["state"];
$result = mysql_query("select schools FROM schools where states='$state' ");
while($school = mysql_fetch_array($result)){
echo"<option value=".$school['schools'].">".$school['schools']."</option>";
}
?>
Dropdown2.php
<?php
include_once("connect.php");
$school=$_POST['school'];
$result = mysql_query("SELECT school_id FROM schools WHERE schools='$school' ");
$school_id = mysql_fetch_array($result);
$id = $school_id['school_id'];
$classname = mysql_query("SELECT DISTINCT class_abrv FROM classes WHERE school_id='$id' ORDER BY class_abrv asc");
while($class = mysql_fetch_array($classname)){
echo"<option value=".$class['class_abrv'].">".$class['class_abrv']."</option>";
}
?>
in second ajax function you have assigned the school drop down box value to state variable but you pass the variable school to ajax post. So there is no school variable that is why you get error.
$("#school").change(function(){
var *state* = $("#school").val();
//above variable should be school.
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+*school*,
success: function(data) {
$("#classname").html(data);
}
});
});

Execute PHP script on same page after selecting a dropdown list option using Ajax or JavaScript

I am creating a MySQL query that will be execute when user select options from more a dropdown lists.
What I want is, on selecting a dropdown list option a query related to that option should be automatically executed using ajax/javascript on the same page. As I have the both html and php code on the same page.
Earlier I was using form submit options for dropdown list but as the number of dropdown option are more than five for filtering the result so queries became complicated to implement. That's why I want to refine result of each dropdown individually.
Any help is appreciated. Thanks in advance!
My HTML code for dropdown list is:
<p>
<label for="experience">Experience :</label>
<select id="experience" name="experience">
<option value="" selected="selected">All</option>
<option value="Fresher">Fresher</option>
<option value="Experienced">Experienced</option>
</select>
</p>
PHP code for executing related queries is:
<?php
if (isset($_GET['exp'])) {
switch ($_GET['exp']) {
case 'Experienced':
$query = "SELECT job_seekers.ID, job_seekers.Name, job_seekers.Skills, job_seekers.Experience FROM job_seekers where job_seekers.Experience!='Fresher'";
break;
case 'Fresher':
$query = "SELECT job_seekers.ID, job_seekers.Name, job_seekers.Skills, job_seekers.Experience FROM job_seekers where job_seekers.Experience='Fresher'";
break;
default:
$query = "SELECT job_seekers.ID, job_seekers.Name, job_seekers.Skills, job_seekers.Experience FROM job_seekers";
}
}
$result = mysql_query($query) or die(mysql_error());
echo "<ul class=\"candidates\">";
while($row = mysql_fetch_row($result))
{
echo "<li>";
echo "<p> <b>ID:</b> <u>$row[0]</u> </p>";
echo "<p> <b>Name :</b> $row[1] </p>";
echo "<p> <b>Key Skills:</b> $row[2] </p>";
echo "<p> <b>Experience:</b> $row[3] </p>";
echo "</li>";
}
echo "</ul>";
?>
When you want to AJAX call a php script, you should you $.ajax provided by Jquery
http://api.jquery.com
so you can use it like so:
$.ajax({
url: 'ajax.php',
data: {
//put parameters here such as which dropdown you are using
},
success: function(response) {
//javascript and jquery code to edit your lists goes in here.
//use response to refer to what was echoed in your php script
}
});
this way, you will have dynamic dropdowns and the refined results you want
<?php
if (isset($_GET['experience'])) {
echo $_GET['experience'];
/* do mysql operations and echo the result here */
exit;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
function myFunction(value)
{
if(value!="All")
{
$.ajax(
{
type: "GET",
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { experience: value},
success: function(data) {
$('#resultDiv').html(data);
}
});
}
else
{
$('#resultDiv').html("Please select a value.");
}
}
</script>
</head>
<body>
<p>
<label for="experience">Experience :</label>
<select id="experience" name="experience" onChange="myFunction(this.value)">
<option value="All" selected="selected">All</option>
<option value="Fresher">Fresher</option>
<option value="Experienced">Experienced</option>
</select>
</p>
<div id="resultDiv">
Please select a value.
</div>
</body>
</html>
You cannot re-execute a PHP part on the same page. Rather use Ajax request to perform the action.

Link dropdown menus populated by mysql php

Excuse me if i've got the terms wrong as i'm new to development, but I have a multiple dropdown menu's linked so that the results from the the previous menu determine what the next menu will populate the next.
i.e. if i select uk, the next list will show, London, If i select Spain, the next list will show Madrid
My dropdown menus are getting populated by mysql, this is fine but how do i link them up without calling on another page
Here's an example of what HTML i have:
<div id="container">
<h3>Price List</h3>
<form method="post" action="" name="form1">
<?
include 'classes.php';
$query="SELECT * FROM Sex_Table";
$result=mysql_query($query);
?>
<div id="select-1">
<select class="calculate" name="sdf" onChange="getClothing(this.value)">
<option value="0">Please Select</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['Price']?> sex_price="<?=$row['Price']?>"><?=$row['Sex_Name']?> (£<?=$row['Price']?>)</option>
<? } ?>
</select>
</div>
<?
$Sex=intval($_GET['Sex_var']);
include 'classes.php';
$query="SELECT * FROM Clothing_Table WHERE Sex_Table_ID='$Sex'";
$result=mysql_query($query);
?>
<div id="select-2">
<select class="calculate" name="sdf" onChange="">
<option value="0">Please Select</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['Price']?> sex_price="<?=$row['Price']?>"><?=$row['Clothing_Name']?> (£<?=$row['Price']?>)</option>
<? } ?>
</select>
</div>
</form>
You'll notice that on change calls on "getClothing(this.value)"
Here is that js:
function getClothing(Sex_Table_ID) {
$.ajax({
type: "get",
url: "findClothing.php",
data: { Sex_var: Sex_Table_ID },
error: function(error) { alert('System error, please try again.'); },
success: function(data){ //data is the response from the called file
$("#select-2").html(data); //this changes the contents of the div to data that was returned
}
});
}
I need it so that it doesn't call on url: "findClothing.php", as once it does this, my price no longer calculates.
I'm sure i don't really need to show this part but just incase, here's what calculates my price:
$(function(){
$('.calculate').change(function() {
var total = 0;
$('.calculate').each(function() {
if($(this).val() != 0) {
total += parseFloat($(this).val());
}
});
$('#total').text('£' + total.toFixed(2));
});
});//]]>
Are you sure your ajax data contains option tag with price as a value?
Also change:
$('.calculate').change(function() {
with
$(".calculate").live("change", function(){

Categories