How to select value from dropdown without using submit - php

I have two dropdowns: state and city. Both are in the same form. The goal is to somehow save the selection without clicking submit button so it could be used as a criteria to display selections of cities in the second dropdown.
For example: When california is chosen in the first dropdown, second dropdwon displays all the cities in California.
Code:
<?php $db= DB::table('states_table')->get(); ?>
<select class="form-control input-md" name="state">
<option value="" disabled selected>Choose the state</option>
<?php foreach ($db as $data) { ?>
<option value="<?php echo $data->city; ?>">
<?php echo $data->city;?>
</option><?php
}?>
</select>

just use ajax :
$('#form').on('change','select[name="state"]', function() {
var province = $('select[name=state]').val();
$.ajax({
url: './get_city.php',
method: 'post',
data: {"state": state},
success: function (data) {
$('select[name=city]').html(data);
}
})
});
and in the get_city.php connect to db , get the cities and return them on tags

$('#state_field_id').click(function(){
var state=document.getElementById('state_field_name').options[document.getElementById('state_field_name').selectedIndex].text;
});
you will get selected value

Related

Populating 2nd select box with the value of first select box

Currently I have 2 select boxes called Country and City. Now I've made it so that the city data is populated according to the value selected in country using AJAX. To do this I've used the following code:
edit.php:
<select name="country" onchange="getcities($(this).val())" required>
<option value="<?php echo set_value('country'); ?>">Select Country</option>
<?php if($countries) foreach($countries as $country): ?>
<option value="<?php echo $country['id']; ?>" <?php echo ($listing[0]['country'] == $country['id'])?'selected="selected"':''?>><?php echo $country['name']; ?></option>
<?php endforeach; ?>
</select>
<label class="control-labels ">City</label>
<div id="emiratewrap">
<select name="emirate" id="emirate">
<option value="">Select City</option>
</select>
AJAX
$(document).ready(function () {
getcities($('#country').val());
});
function getcities(obj){
console.log(obj);
var dataString = new Object();
dataString.emirate = '<?php echo $property->emirate ?>';
$.ajax({
type: "get",
dataType:"json",
url: "<?php echo site_url('listings/ajaxgetcitiesedit'); ?>/"+obj,
data: dataString,
success: function(e) { $('#emiratewrap').html(e.result);
$bb = "<?php echo $property->status; ?>";
if($bb=="Y") {$("#emiratewrap select").addClass("disabled"); }
}
});
}
Controller:
function ajaxgetcitiesedit($country=''){
$emirate = $this->input->get('emirate');
if(!$country) return false;
$cities = $this->listings_model->get_activepair_cities(array('country_id'=>$country),'*','name asc');
$html = '<select name="emirate" id="emirate" class="form-control select2 required" onchange="oemirate(this);">';
$html .= ($emirate <1)? '<option value="">Select Emirate</option>':'';
foreach($cities as $city):
$html .= '<option value="'.$city['id'].'" '.($city['id'] == $emirate ? 'selected="selected"' : '').'>'.$city['name'].'</option>';
endforeach;
$html .= '<option value="Other">Other</option> </select><input type="text" id="other_emirate" name="other_emirate" class="form-control" style="display: none;" />';
echo json_encode(array('result'=>$html));
}
Now currently I'm working on edit page where it should initially show what value the user had selected while adding the entry. As of now the functionality of the second select works fine as intended as it changes its options when the 1st select data is changed and also gives the correct value in database when update is pressed.
Now the only problem here I have is that initially when loading into the page, it doesn't show anything in the second select box even though there is a value for it in the database. I performed a console.log(obj); in getcities(obj) and initially it returned undefined and everytime I change country, it gives a value in my log.

PHP: Passing selected list value to another variable in the same page

I have a form, having two list boxes and based on the selected field from the first list, I have to fetch data from the database to create second list box.
I am trying to acheive this with post method, but unable to understand why mey second list is not populating with data...
PHP to fetch data for second list box
if (isset($_POST['val']))
{
$value = $_POST['val'];
$smt3 = $db->prepare('select floor from test where name_id =?');
$smt3->execute(array($value));
$HF_id = $smt3->fetchAll();
}
HTML to for the list boxes
<select class="Name" name="Profile_Name1" id="PC1">
<option value="A">AA</option>
<option value="B">BB</option>
<option value="c">CC</option>
<option value="d">DD</option>
</select>
<label>Home Floor </label>
<select name="Home_Floor" id="hfid"> <br />
<option value="">Home_Floor</option>
<?php foreach ($HF_id as $row){echo '<option value="' . $row['floor'] . '">' . $row ['floor'] . '</option>';}?>
</select>
Jquery
$('#PC1').on('click', function() {
$.post('user_info1.php', 'val=' + $(this).val(), function (response) {
$.ajax({
url: 'user_info1.php', //This is the current doc
type: "POST",
data: ({val: + $(this).val()}),
success: function(data){
}
});
You seem to expect the post function to trigger a loading of the page specified by the URL parameter.
Try something along the lines of this:
HTML
<select class="Name" name="Profile_Name1" id="PC1">
<option value="A">AA</option>
<option value="B">BB</option>
<option value="C">CC</option>
<option value="D">DD</option>
</select>
<label>Home Floor </label>
<select name="Home_Floor" id="hfid">
</select>
loaddata.php
if (isset($_POST['val']))
{
$value = $_POST['val'];
$smt3 = $db->prepare('select floor from test where name_id =?');
$smt3->execute(array($value));
$HF_id = $smt3->fetchAll();
$HF_array=array();
foreach ($HF_id as $row)
{
$HF_array[]=$row['floor'];
}
}
echo json_encode($HF_array);
javascript/jquery
jQuery('#PC1').on('click', function() {
jQuery.ajax({
url: 'loaddata.php',
type: "POST",
data: ({val: + $(this).val()}),
success: function(data){
//data should come as JSON string in the form of ['item1','item2','item3'] use JSON.parse to convert to object:
jQuery.each(JSON.parse(data), function(key, datavalue) {
jQuery('#hfid').append(
jQuery('<option>', { value : datavalue })
.text(datavalue)
);//end of append
});//end of each
}//end of success function
});//end of ajax datastruct and ajax call
});//end of on-click-function

How to pass selected options from a dropdown menu to another page using AJAX

I have a problem on passing more than one values from a dropdown menu. What I am doing is an attendance system where a dropdown menu containing the choices of attendance status per student. User will then choose the attendance status of each student accordingly, and what I am trying to do is to pass the status that has been chosen to another page.
I am trying to insert the selected attendance status into an array using AJAX and then pass the array to another page. Here's what I have so far:
todaysattendance.php
//dropdown menu
<tr>
<td> $fetched_fName $fetched_lName </td>
<td> <select name='okselect' id='okselect'>
<option value='no'> </option>
<option value='p' name='p' style='color:green; font-weight:bold;'>Present</option>
<option value='ea' name='ea' style='color:#e1c872; font-weight:bold;'>Excused Absent</option>
<option value='ua' name='ua' style='color:#e34c4c; font-weight:bold;'>Unexcused Absent</option>
<option value='et' name='et' style='color:blue; font-weight:bold;'>Excused Tardy</option>
<option value='ut' name='ut' style='color:purple; font-weight:bold;'>Unexcused Tardy</option>
<option value='sr' name='sr' style='color:black; font-weight:bold;'>School's Representative</option>
</select></td> </tr>
todaysattendance.php
//AJAX code
var tempArr = [];
$("#okselect").change(function()
{
var output = getValues(this, function ()
{
for (var i=0;i<output.length;i++)
{
tempArr.push(output);
};
});
$.ajax({
type: "POST",
url: "add_attendance_check.php",
data: {tempArr: tempArr},
success: function(data) {
//
},
error: function(e) {
console.log(e.message);
}
});
});
add_attendance_check.php
$passed_attstatus = array();
$thestatus = $_POST['tempArr'];
array_push($passed_attstatus, $thestatus);
But from this coding, let's say I took the attendance status for 10 students, I only managed to get the last student's attendance status. I need help on this. Thank you very much in advance!
print variable dropdown_value in add_attendance_check you will get the value of selected dropdown.
<form method="post" action="" role="search">
<select name='okselect' id='okselect'>
<option value='no'> </option>
<option value='p' name='p' style='color:green; font-weight:bold;'>Present</option>
<option value='ea' name='ea' style='color:#e1c872; font-weight:bold;'>Excused Absent</option>
<option value='ua' name='ua' style='color:#e34c4c; font-weight:bold;'>Unexcused Absent</option>
<option value='et' name='et' style='color:blue; font-weight:bold;'>Excused Tardy</option>
<option value='ut' name='ut' style='color:purple; font-weight:bold;'>Unexcused Tardy</option>
<option value='sr' name='sr' style='color:black; font-weight:bold;'>School's Representative</option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
jQuery(document).ready(function() {
jQuery("#okselect").change(function() {
var dropdown_value = $('#okselect').val();
$.ajax({
type: "POST",
url: "add_attendance_check.php",
data: {dropdown_value: dropdown_value},
success: function(data) {
//
},
error: function(e) {
console.log(e.message);
}
});
});
});
</script>
I have a great news, I finally solved the problem. All I need to do is to change this line in todaysattendance.php from
<select name='okselect' id='okselect'>
into
<select name='okselect[]' id='okselect'>
In add_attendance_check.php, I simply changed to
$passed_attstatus = array();
$thestatus = $_POST['okselect'];
array_push($passed_attstatus, $thestatus);
No need for AJAX from the very beginning. Anyway I would like to thank everyone who responded. Have a good day!
<select name='okselect' id='okselect' onchange="abc(this.value)">
//your option
</select>
And Ajax call abc function inner abc(value)

Create dynamic drop down box

I am trying to create a dependent dynamic drop down box on three input fields. At the moment the each input field is getting their data from their individual tables called tour_type, countries and destination. This is the form:
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required>
<option value="" selected="selected">--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country </label>
<select id="country" name="country" class="country" required>
<option value="" selected="selected">-- Select --</option>
<?php
$sql=mysql_query("SELECT * FROM `countries` where `tour_type_id` = ?"); //what should i put in here?
while($row=mysql_fetch_array($sql))
{
$cid=$row['countries_id'];
$name=$row['countries_name'];
echo "<option value='$cid'>".$name."</option>";
}
?>
</select>
<label>Destination </label>
<select id="destination" name="destination" class="destination" required>
<option value="" selected="selected">-- Select --</option>
<?php
$sql=mysql_query("SELECT * FROM `destination` where `countries_id` = ?");//what should i put in here?
while($row=mysql_fetch_array($sql))
{
$destination_id=$row['destination_id'];
$name=$row['destination_name'];
echo "<option value='$destination_id'>".$name."</option>";
}
?>
</select>
This is the javascript at the top of the form
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$(".destination").html(html);
}
});
});
});
</script>
Finally these are the 3 tables i.e. tour_type, countries and destination respectively:
Can anyone help me on this?
How do I make each drop down box dependable on each other? For e.g. If i select Culture on the 1st drop down, then only Holland and Belgium should show in the 2nd drop down. So now if i select Holland from 2nd drop down, then Amsterdam should show in the 3rd drop down.
This is the ajax.php which i am not too sure if it is right.
<?php
include('../config.php');
if($_POST['']) //what should i put in here?
{
$id=$_POST['']; //what should i put in here?
$sql=mysql_query //this is where i do not know what to put;
while($row=mysql_fetch_array($sql))
{
//And what should i be placing here
}
}
?>
This is what the web front end form looks like after implementing the code provided by dianuj. I still can not select the 2nd and 3rd drop down boxes:
So first you have the tour type select box. So just move the code for fetching countries based on tour type to ajax.php. Also include one more parameter to distinguish which type(tour type,country etc) you are posting. so you will get the id and based on the type parameter you can fetch from different tables. Then create a selectbox HTML snippet and output it. This will return for the AJAX call and you can insert the HTML.
You can use ajax get here and can use the shorthand version like
$.get('ajax,php?id=idhere&type=country', function(data) {
$('#country_result').html(data);
});
Where result is the id of div to which the select box has to be inserted.
So the HTML part will be like
<div id="country_result"></div> //Country select box goes here
<div id="destination_result"></div> //Country select box goes here
The simplest approach is to fetch select options from the server when the selections change, like so:
$('#tour_type').change(function() {
// load country options
});
$('#country').change(function() {
// load destination options
});
The server should simply return a snippet of HTML containing the available options for country and destination.
here you go you have to fetch the options from the ajax.php do not place the query in second dropdown
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required>
<option value="" >--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country </label>
<select id="country" name="country" class="country" required>
<option value="">-- Select --</option>
</select>
<label>Destination </label>
<select id="destination" name="destination" class="destination" required>
<option value="">-- Select --</option>
</select>
initially country and destination drop down should be empty here your js goes
$('#tour_type').change(function() {
var id=$(this).val();
$.ajax
({
type: "POST",
url: "ajax.php",
data: "&id="+id+"&get_countries=1",
success: function(html)
{
$("#country").append(html);
}
});
});
$('#country').change(function() {
var id=$(this).val();
$.ajax
({
type: "POST",
url: "ajax.php",
data: "&id="+id+"&get_destination=1",
success: function(html)
{
$("#destination").append(html);
}
});
});
And your ajax.php
<?php
if($_REQUEST['get_countries']){
$sql=mysql_query("SELECT * FROM `countries` where `tour_type_id`=".$_REQUEST['id']);
$countries="";
while($row=mysql_fetch_array($sql))
{
$cid=$row['countries_id'];
$name=$row['countries_name'];
$countries.= "<option value='".$cid."'>".$name."</option>";
}
echo $countries;
}elseif($_REQUEST['get_destination']){
$destination="";
$sql=mysql_query("SELECT * FROM `destination` where `country_id` =".$_REQUEST['id'])
while($row=mysql_fetch_array($sql))
{
$destination_id=$row['destination_id'];
$name=$row['destination_name'];
$destination.= "<option value='".$destination_id."'>".$name."</option>";
}
echo $destination;
}
?>
Hope it works fine
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required onchange="get_country($(this).val())">
<option value="" selected="selected">--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country </label>
<select id="country" name="country" class="country" required onchange="get_destination($(this).val())">
<option value="" selected="selected">-- Select --</option>
</select>
<label>Destination </label>
<select id="destination" name="destination" class="destination" required>
<option value="" selected="selected">-- Select --</option>
</select>
<script>
function get_country(tour_type)
{
$.post("ajax.php",{get_country:tour_type},function(data){
var data_array = data.split(";");
var number_of_name = data_array.length-1;
var value;
var text;
var opt;
var temp_array;
for(var i=0; i<number_of_name; i++)
{
value=temp_array[i];
//alert(value);
text=temp_array[i];
opt = new Option(text,value);
$('#country').append(opt);
$(opt).text(text);
}
$("#country").prop("disabled", false);
});
}
//same way script for getting destination
</script>
// now in ajax file
if(isset($_POST["get_country"]))
{
$tour_type = str_replace("'","",stripslashes(htmlentities(strip_tags($_POST["get_country"]))));
$country_select = mysql_query("select * from country where tour_type_id = '$tour_type'");
$country="";
while($country_row = mysql_fetch_array($country_select))
{
$country = $country.$country_row["country"].";";
}
echo $country;
}
// same way ajax for destination

Using AJAX to Change Form Input Options Based on Previous Selection

I have a form on my page which contains two select dropdowns. The first one lets the user choose a country, and the second one lets the user choose a city from that country. I would like for the second dropdown options to be filled with cities based on the previously selected country. Currently, I have an onChange event that leads to an AJAX script which populates the cities from an external php file. Here is my code so far:
HTML Form
<form method="post">
<select name="country" onchange="dynamic_Select('city.php', this.value)" />
<option value="#">-Select-</option>
<option value="India">India</option>
<option value="USA">USA</option>
</select>
<div id="txtResult">
<select name="cityList">
<option></option>
</select>
</div>
</form>
AJAX Script in Header (dynamic_Select)
<script>
function dynamic_Select(ajax_page, country) {
$.ajax({
type: "GET",
url: ajax_page,
data: "ch=" + country,
dataType: "text/html", //<--UPDATE: DELETING THIS LINE FIXES EVERYTHING
//<--UPDATE2: DON'T DELETE; REPLACE "test/html" with "html"
success: function(html){ $("#txtResult").html(html); }
});
}
</script>
//I also have a link to the jquery file
<script src="js/jquery.js" type="text/javascript"></script>
External PHP File (city.php)
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// List of cities for India
if ($_GET['ch'] == 'India') {
?>
<select name="cityList">
<option value="Mumbai">Mumbai</option>
<option value="Delhi">Delhi</option>
<option value="Bangalore">Bangalore</option>
<option value="Patna">Patna</option>
</select>
<?php
}
// List of cities for USA
if ($_GET['ch'] == 'USA') {
?>
<select name="cityList">
<option value="Albama">Albama</option>
<option value="Alaska">Alaska</option>
<option value="Arizona">Arizona</option>
<option value="Florida">Florida</option>
</select>
<?php
}
?>
The above set of code isn't working, and I can't figure out why. Two dropdown lists appear on the page (the second one is initially blank), but after choosing a country from the first dropdown the second dropdown remains blank. Any help would be much appreciated!
Change your dataType parameter from "text/html" to "html".
Also, you could have shortened all of this:
function dynamic_Select(ajax_page, country) {
$.ajax({
type: "GET",
url: ajax_page,
data: "ch=" + country,
dataType: "text/html", //<--UPDATE: DELETING THIS LINE FIXES EVERYTHING
//<--UPDATE2: DON'T DELETE; REPLACE "test/html" with "html"
success: function(html){ $("#txtResult").html(html); }
});
}
To:
function dynamic_Select(ajax_page, country) {
$.get(ajax_page, {ch: country}, function(h) {
$('#txtResult').html(h);
});
}

Categories