i have two list box for countries and states. when i click on a country for ex. India, the corresponding states appears in the states list. but the same should happen for more than one country. if i select two countries, the states of the both countries should be added in the states list.
javascript code for countries list-
$('#pcountries').on('change', function() {
var country_id = this.value;
$.ajax({
type: "POST",
url: "php_includes/select_list_pstate.php",
data: 'country_id=' + country_id,
success: function (result) {
$("#pstate").append(result);
}
});
});
php code-
if ($_POST['country_id']) {
$country_id = $_POST['country_id'];
if ($country_id != '') {
$states_result = $db_conx->query('select * from states where countryId=' . $country_id . '');
$options = "<option value=''>Any</option>";
while ($row = $states_result->fetch_assoc()) {
$options .= "<option value='" . $row['stateId'] . "'>" . $row['state'] . "</option>";
}
echo $options;
}
}
Multiple Select returns an array you need to use in instead of = in query like this
$states_result = $db_conx->query("select * from states where countryId IN (".implode(',',$country_id ).")";);
var selectedValues = $('#multipleSelect').val();
console.log(selectedValues)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="multipleSelect" multiple="multiple">
<option value="1" selected>Text 1</option>
<option value="2" selected>Text 2</option>
<option value="3">Text 3</option>
</select>
Related
I am new at development, right now I am learning laravel 9 and I am trying to get a dependent dropdown selected value. Here is my blade file:
<div class="form-group">
<label for="vendor_state">State</label>
<select class="form-control" style="color: #000;" id="vendor_state" name="vendor_state">
<option selected disabled>Select State</option> #foreach ($states as $state)
<option value="{{ $state->id }}" #if(!empty($state->id==$vendorDetails['state'])) selected #endif>{{ $state->name }}</option> #endforeach
</select>
</div>
<div class="form-group">
<label for="vendor_city">City</label>
<select class="form-control" style="color: #000;" id="vendor_city" name="vendor_city"></select>
</div>
And here is the script:
<script type="text/javascript">
$(document).ready(function () {
$('#vendor_state').on('change', function () {
var stateId = this.value;
$('#vendor_city').html('');
$.ajax({
headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{ route('cities') }}?state_id='+stateId,
type: 'get',
success: function (res) {
var dropdown = $('#vendor_city');
dropdown.html('<option selected disabled value="">Select City</option>');
$.each(res, function (key, value) {
dropdown.append('<option value="' + value.id + '">' + value.name + '</option>');
});
}
});
});
});
</script>
For now, I can save the values of the state and the city in the database and get the selected value of the state. How can I get the selected value of the city?
I tried storing the selected value in dropdown var and display it using if condition inside the option value of the script.
Some time ago, I wrote a similar script for another system. Chose country, then a dropdown with Regions(states) list appears. Upon Choosing a region, a list of Departments (Cities) appears.
Note:
In the database, I have relations from Regions (states) to Countries and from Departments to regions. I.e.:
In the Regions database table, I have a field named "country_id", and in the Departments table I have a column "region_id"
My code was as follows:
The main page with the dropdowns
//Country drop-down select
<select style="max-width:150px;" name="country_id" id="country-list" onChange="getRegion(this.value);">
//Options with list of countries names and ID in foreach loop
<option value="' . $country->id . '">' . $country->name . '</option>
</select>
<select name="region_id" id="region-list" onChange="getDepartment(this.value);">
<option value=""><?= $langs->trans('SelectRegion') ?></option>
</select>
<select name="department_id" id="department-list" class="demoInputBox">
<option value=""><?= $langs->trans('SelectDepartment') ?></option>
</select>
The AJAx function:
function getRegion(val) {
$.ajax({
type: "POST",
url: "region.inc.php",
data: 'country_id=' + val,
success: function (data) {
$("#region-list").html(data);
}
});
}
function selectCountry(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
function getDepartment(val) {
$.ajax({
type: "POST",
url: "department.inc.php",
data: 'region_id=' + val,
success: function (data) {
$("#department-list").html(data);
}
});
}
function selectRegion(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
"region.inc.php" is:
$country_id = $_POST['country_id'];
<option value=""><?= $langs->trans('SelectRegion') ?></option>
$regions_array = function_to_get_regions_ids_and_names_in_array
foreach ($regions_array as $result) {
print '<option value="' . $result->region_id . '">' . $result->department_id . '</option>';
}
"departments.inc.php"
$region_id = $_POST['region_id'];
$departments_array = function_to_get_departments_ids_and_names_in_array
<option value=""><?= $langs->trans('SelectDepartment') ?></option>
foreach ($departments_array as $result) {
print '<option value="' . $result->department_id . '">' . $result->department_name . '</option>';
}
I have two select boxes in which I want to select a value for one and the second select box should get same value.
Currently I am passing id and want my designation also to pass to ajax. Can I know how this can be implemented via ajax. Any help will be highly appreciated.
<select name="designation" class="form-control" id="desig" >
<option value="">Select a Designation/Role</option>
<?php
$sql = mysql_query("SELECT id, designation FROM tbl where status =1 and designationtype_id = 1 ");
while ($rows = mysql_fetch_assoc($sql)){
echo "<option value=" . $rows['id'] . ">" . $rows['designation'] . "</option>";
}
?> <select name="dd" id="dd" class="form-control" disabled>
<option value=""></option>
</select>
My AJAX,
<script type="text/javascript">
$(document).ready(function() {
$("#desig").change(function() {
var id = $(this).val();
var dataString1 = 'id=' + id;
var des = $(this).val();
var dataString2 = 'designationname=' + des;
$.ajax({
type: "POST",
url: "escalation_ajax.php",
data: dataString,
cache: false,
success: function(html) {
var data = html.split(",");
$('#rephead').val(data[0]);
}
});
});
});
</script>
escalation_ajax.php
<?php
if ($_POST['id'])
{
if ($_POST['des'])
{
$des_id = $_POST['id'];
$designation = $_POST['des'];
$sql = mysql_query("SELECT designation_id, reporting_head FROM aafmindia_in_sbi.tbl_reporting_head WHERE status=1 and reporting_head_for='$des_id'");
if ($sql === FALSE)
{
trigger_error('Query failed returning error: ' . mysql_error() , E_USER_ERROR);
}
else
{
while ($row = mysql_fetch_array($sql))
{
$id = $row['designation_id'];
$reporting_head = $row['reporting_head'];
echo '<option value="' . $id . '">' . $reporting_head . '</option>' . ',' . '<option value="' . $des_id . '">' . $designation . '</option>';
}
}
}
}
?>
What you could do, is have the second select (the one that needs the same value as the first) in a seperate file that you load via AJAX.
AJAX function:
function selection()
{
var selectValue=$("select#dd option:selected").val();
$.ajax({
type : "POST",
url : "escalation_ajax.php",
data : { id : selectValue },
success: function (html) {
$("#secondSelectorDiv").html(html);
}
})
}
What this does, is that when the selection() function is called, it will post the selected value of the first select to "escalation_ajax.php". It will then load that page into an element (div element in my example) with the id "secondSelectorDiv".
The html for the select with the function (which I will call onchange in this example), can look like this:
<select id="dd" onchange="selection();">
<option value=""></option>
</select>
<div id="secondSelectorDiv"></div>
Now in escalation_ajax.php you can retrieve the post variable and use it to look for the id in question for the second select.
<?php
$id=$_POST['id'];
/*
If you're using the id to fetch something in your database,
which it looks like you're doing, then use the post variable
to fetch your rows and build the select from that.
*/
$sql="SELECT * FROM table_name WHERE id='$id'";
$result_set=mysql_query($sql);
$row=mysql_fetch_array($result_set);
$count=mysql_num_rows(result_set);
$counter=0;
//this is the id you will check for in order to see what's to be selected
$idToCheck=$row['id'];
?>
<select id="dd2">
while($count > $counter)
{
counter++;
echo '<option value=""'; if($idToCheck == $id){ echo 'selected="selected"'; } echo '></option>';
}
?>
If you want the second select to be displayed before the first select has a value, you can simply just call an AJAX function that loads in the second select on page load.
IMPORTANT!: You should really switch to mysqli_* or PDO instead of using the deprecated mysql_*. You should at the very least look into sanitizing your inputs.
I have an select menu that submits without reloading the page as follows:
<select id="option" name="option">
<option value="15">15/option>
<option value"30">30</option>
<option value"90">90</option>
</select>
It will submit to the current page as follows, without reloading the page
<script type="text/javascript">
$('#option').change(function(){
var option_val = $(this).val();
$.ajax({
type: 'post',
url: "$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];",
data: "option="+option_val,
success: function(data)
{
window.alert(data)
}
});
});
</script>
The result of a change in the option menu is an popup window with all the code of the page echoed back.
What i want to do on the page is use the $_POST['option'] that is submitted and recalculate a price for example
<body>
//some code and div's
<?php
if (isset($_POST['option'])) {
$option = $_POST['option'];
$price= $row_product['price'] + $option;
echo $price;
} ?>
</body>
The are several places where I would like to use the submitted option value
Any help welcome
Sorry if it is very obvious
The only way is making a PHP page that does the calculation
HTML/page1.php
<select id="option" name="option">
<option value="15">15</option>
<option value="30">30</option>
<option value="90">90</option>
</select>
<div id="dynamic">
<p>DEFAULT CONTENT</p>
</div>
HTML/page2.php
$option = 0;
if(isset($_GET["option"])){
$option = $_GET["option"];
}
//do calculations
echo "<my-html-stuff>lorem ipsum</my-html-stuff>";
JS
var dynamic = $("#dynamic");
$('#select').on("change", function() {
var selected = $(this).val();
dynamic.load("page2.php?option=" + selected, function() {
dynamic.html("<p>CONTENT OPTION "+selected+"</p>");
});
});
Fiddle ==> https://jsfiddle.net/tonysamperi/4dbwwn3g/
WITH JSON
page2.php
header('Content-Type: application/json');
$option = 0;
if(isset($_GET["option"])){
$option = $_GET["option"];
}
$response = ["result" => $option];
echo json_encode($response);
JS
$('#select').on("change", function() {
var selected = $(this).val();
$.get("page2.php?option=" + selected, function(response) {
//do stuff with data
console.debug("RESPONSE", response);
});
});
Html file
The values for the sub combobox is retrieved by a php select query and the values are characters.
i have tried with integers values are perfectly passed.
<select name="sub" id="sub">
<option value="">Select semester first</option>
</select>
<select name="staff" id="staff">
<option value="">Select sub first</option>
</select>
Javascript
$('#sub').on('change',function(){
var SUB = $(this).val();
if(1){
$.ajax({
type:'POST',
url:'sta.php',
data:'sub='+SUB,//character is not passing.
success:function(html){
$('#staff').html(html);
}
});
}else{
$('#staff').html('<option value="">Select sub first</option>');
}
});
php file
if(isset($_POST["sub"]) && !empty($_POST["sub"]))
{
//Get all city data
$query = mysql_query("SELECT staff_name FROM subject WHERE course_name = ".$_POST['sub']);
//Count total number of rows
$rowCount = mysql_num_rows($query);//It always shows 0
//Display cities list
if($rowCount > 0){
echo '<option value="">Select staff</option>';
while($row = mysql_fetch_assoc($query)){
echo '<option value='.$row['staff_name'].'>'.$row['staff_name'].'</option>';
}
}else{
echo '<option value="">staff not available</option>';//when i tried to execute it comes here
}
}
There is simple syntactical error in your query in php just rewrite it as:
$query = mysql_query("SELECT staff_name FROM subject WHERE course_name = '".$_POST['sub']."'");
wherever you pass the data other than numbers always use single inverted comma such as'myData' to surround the values.
I'm working on a form. There are select elements and their options are from a database.
When i choose the first (for example a school class) the second have to show only those names who are in the class selected at first, from database too.
I'm rookie at Javascript and JQuery so I'm okay with page refreshing PHP solutions but I can't figure it out on my own. Can you please give me some instructions or advices how to start to work on this?
You can achieve this with ajax using preferably jquery and json.
javascript/ajax:
function fillSecondSelect()
{
$.get("ajaxFill.php?id=" + $("#class").val(),"",function(data) {
var selectData = "<option value=''> - Choose Student - </option>";
data = JSON.parse(data);
for(i=0;i<data.length;i++)
{
selectData += "<option value='" + data[i].id + "'>" + data[i].name + "</option>";
}
$("#students").html(selectData);
});
}
html:
<select id="class" name="class" onchange="fillSecondSelect()">
<option value=""> - Choose Class - </option>
<option value='1'>Class A</option>
<option value='2'>Class B</option>
</select>
<select id="students" name="students"></select>
ajaxFill.php (which should get the student data according the class id sent from mysql and serve it as JSON):
$result = mysqli_query($link,"SELECT * FROM students WHERE class_id = '" . $_GET['id'] . "'") or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($result))
{
$students[] = array("id" => $row['student_id'], "name" => $row['student_name']);
}
echo json_encode($students);
You use Jquery and Ajax to fetch the Students in a class based on the Class selected and load the student list into a Select element without refreshing the page.
HTML
<select id="selectedclass" onBlur="loadstudent();">
<option>class 1</option>
<option>class 2</option>
<option>class 1</option>
</select>
<select id="students" ></select>
Javascript
function loadstudent(){
var selectedclass = $('selectedclass').val();//user id
$.ajax({
type:'POST',
url: your php script,
data: 'selectedclass='+selectedclass,
dataType: 'json',
success: function(data)
{
var classlist='', html;
for(var i = 0; i < data.length; i++) {
classlist = data[i];
html+=classlist.students
}
//get number of outbox
$('#students').html(html);
},
error: function(jqXHR, exception) {
alert('Error');
}
});
}
PHP
<?php
include "config.php";//database connection file
//database using PDO
$db = pdoDB::getConnection();
//data from html
$student_class=$_POST['selectedclass'];
$query = "SELECT student_lastName,student_firstName
FROM student_table WHERE student_class='student_class'";
$result = $dbase->query($query) or die("failed!");
while ($row = $result->fetch(PDO::FETCH_BOTH)){
//credits info
$studentlist="<option>".$row['student_lastName']." ".$row['student_firstName']."</option>";
$results[] = array("students"=>$studentlist);
}
header('Content-type:application/json');
exit (json_encode($results));
?>
The data sent from the PHP script should be encoded with JSON
Modern websites use ajax to do this.
After the first item is selected an ajax request is sent which delivers the data for the second select.
There are many ways to build the second select. The ajax response could contain a json array with all the data and then you build the select field with js.
Or the response delivers complete html and all you have to do is to insert it.
I think this is exactly that you mean: http://codepen.io/man/pen/oBFlE
Put the js code in your file. You can have as many levels as you want. Explaining:
<select name="level1"><!--this is the "main" select-->
<option value="level2A">Level2A</option>
<option value="level2A">Level2B</option>
</select>
<select name="level2A"><!--this shows when the user selects the option with name ""level2A"-->
<option value="level3"></option>
</select>
<select name="level2B">
<!--options...-->
</select>
<select name="level3"></select>