Today, I went to code a form with Dynamic dropwdown list in it.
Mission : I want to make dynamic dropdown list when User choose Category, then the store with that category will appear.
It is the form :
<select name="category" class="form-control" id="category" onchange="ajaxStore(this.value)">
<option value="-1"> - Choose Category -</option>
<?php
$StoreCategoriesAPIAccessor = new StoreCategoriesAPIService(GuzzleClient::getClient());
$stores = $StoreCategoriesAPIAccessor->getStoreCategories();
foreach ($stores as $store):
?>
<option value="<?php echo $store->getStoreCategoryId(); ?>"><?php echo $store->getCategory(); ?></option>
<?php endforeach; ?>
</select>
<label for="inputName" class="control-label">Store Name</label>
<select name="store" class="form-control" id="store">
<option value="-1"> - Choose Store -</option>
</select>
This is the AJAX :
<!-- linking drop down AJAX -->
<script type="text/javascript">
var ajaxku=buatajax();
function ajaxStore(id){
var url="objects/StoreAPIService.php?category="+id+"&sid="+Math.random();
ajaxku.onreadystatechange=stateChanged;
ajaxku.open("GET",url,true);
ajaxku.send(null);
}
function buatajax(){
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}
if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function stateChanged(){
var data;
if (ajaxku.readyState==4){
data=ajaxku.responseText;
if(data.length>=0){
document.getElementById("store").innerHTML = data
}else{
document.getElementById("store").value = "<option selected>- Choose Store -</option>";
}
}
}
</script>
And this the code of StoreAPIService.php :
session_start();
$stores = array();
$store_category_id = $_GET['category'];
try
{
//$client = new GuzzleClient();
$response = $this->client->get('admin/store/bycat/rev/'.$store_category_id,
['headers' => ['Authorization' => $_SESSION['login']['apiKey']]
]);
$statusCode = $response->getStatusCode();
// Check that the request is successful.
if ($statusCode == 200)
{
$error = $response->json();
echo"<option value=''>- Choose Store -</option>";
foreach ($error['stores'] as $store)
{
$mainStore = new StoreSummary();
echo "<option value='{$mainStore->setStoreId($store['store_id'])};'>{$mainStore->setStoreName($store['store_name'])};</option>";
array_push($stores, $mainStore);
}
}
}
I got no error, but the Store with 'Category' that I Choose is not appearing.
Could anyone please check if I went wrong.
thanks for your helps.
You were trying to change options of a dropdown menu. i did this by changing dropdown menu itself.
I created a div with id="store" in the html form and changing the innerHTML of div using ajax
html form
<select name="category" class="form-control" id="category" onchange="ajaxStore(this.value)">
<option value="-1"> - Choose Category -</option>
<?php
$StoreCategoriesAPIAccessor = new StoreCategoriesAPIService(GuzzleClient::getClient());
$stores = $StoreCategoriesAPIAccessor->getStoreCategories();
foreach ($stores as $store):
?>
<option value="<?php echo $store->getStoreCategoryId(); ?>"><?php echo $store->getCategory(); ?></option>
<?php endforeach; ?>
</select><label for="inputName" class="control-label">Store Name</label>
<div id="store"><select name="store" class="form-control">
<option value="-1"> - Choose Store -</option>
</select>
</div> <!--end of store -->
ajax code
<!-- linking drop down AJAX -->
<script type="text/javascript">
var ajaxku=buatajax();
function ajaxStore(id){
var url="objects/StoreAPIService.php?category="+id+"&sid="+Math.random();
ajaxku.onreadystatechange=stateChanged;
ajaxku.open("GET",url,true);
ajaxku.send(null);
}
function buatajax(){
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}
if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function stateChanged(){
var data;
if (ajaxku.readyState==4){
data=ajaxku.responseText;
if(data.length>=0){
document.getElementById("store").innerHTML = data
}else{
document.getElementById("store").value = "<select name=\"store\" class=\"form-control\">
<option value=\"-1\"> - Choose Store -</option>
</select>";
}
}
}
</script>
StoreAPIService.php :
session_start();
$stores = array();
$store_category_id = $_GET['category'];
try
{
//$client = new GuzzleClient();
$response = $this->client->get('admin/store/bycat/rev/'.$store_category_id,
['headers' => ['Authorization' => $_SESSION['login']['apiKey']]
]);
$statusCode = $response->getStatusCode();
// Check that the request is successful.
if ($statusCode == 200)
{
$error = $response->json();
echo "<select name=\"store\" class=\"form-control\">
<option value=\"\">- Choose Store -</option>";
foreach ($error['stores'] as $store)
{
$mainStore = new StoreSummary();
echo "<option value='{$mainStore->setStoreId($store['store_id'])};'>{$mainStore->setStoreName($store['store_name'])};</option>";
array_push($stores, $mainStore);
}//end of foreach
echo "</select>"
}
}
Related
I'm using select2 plugin to show my dropdown data .
I have problem , because my dropdown select2 have 18000 data .
How it is so that the data displayed in part, not all data is loaded. I use the Medoo database framework. how do i do it?
This my source code .
<div class="form-group">
<label for="nama_user"><?php _e('Nama User'); ?></label>
<select class="form-control select2 select2-hidden-accessible" id="nama_user" name="nama_user" style="width: 100%;" tabindex="-1" aria-hidden="true">
<option value="0"><?php _e('Nobody'); ?></option>
<?php foreach ($ldap as $ldap) { ?>
<option value='<?php echo $ldap['id']; ?>'><?php echo $ldap['nama_user']; ?></option>
<?php } ?>
</select>
</div>
This code for jquery .
$(".select2").select2();
$(".select2tag").select2({
tags: true,
maximumSelectionLength: 1
});
$(".select2tags").select2({
tags: true
});
This Function for call data with Medoo
case "gemilang/add":
$contacts = getTable("contacts");
if($isAdmin) { $assets = getTable("assets"); } else { $assets = getTableFiltered("assets","clientid",$liu['clientid']); }
$clients = getTable("clients");
$cabang_gemilang = getTable("cabang_gemilang");
$ldap = getTable("ldap");
$admins = getTableFiltered("people","type","admin");
if($isAdmin) { $users = getTableFiltered("people","type","user"); } else { $users = getTableFiltered("people","type","user","clientid",$liu['clientid']); }
break;
Ok so I have three tables which contains list World's countries their states and their cities for my registration form. The problem is that the list of the cities is too huge. It contains 48,314 entries in total. So my site is getting hanged and the browser is showing messages to stop script. I am using mozilla for browser purpose.
This is the code I am using to get the cities, states and countries:
$country = "SELECT * FROM countries";
$country = $pdo->prepare($country);
$country->execute();
$state = "SELECT * FROM states";
$state = $pdo->prepare($state);
$state->execute();
$city = "SELECT * FROM cities";
$citq = $pdo->prepare($city);
$citq->execute();
This is my jQuery code:
$(document).ready(function () {
$("#country").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#state option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#state').html('<option value="">Select State</option>').append(options);
});
$("#state").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#city option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#city').html('<option value="">Select City</option>').append(options);
});
});
This is my HTML:
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="state" id="state">
<option value="">Select State</option>
<?php while($j = $state->fetch()){ extract($j); ?>
<option value="<?php echo $country_id; ?>" data="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="city" id="city">
<option value="">Select City</option>
<?php while($k = $citq->fetch()){ extract($k); ?>
<option value="<?php echo $id ; ?>" data="<?php echo $state_id; ?>"><?php echo $name ; ?></option>
<?php } ?>
</select>
Now can anyone please help me getting a solution as to how I can load it completely smoothly without getting my site hanged whenever the page is refreshed?
You could load the states and cities dynamically once the "parent" selection is made. This would reduce the amount of data.
No clear code because I think you know what you are doing, but the idea:
-> [html] select
-> [js] onChange call php with ajax
-> [php] SQL select states where country="chosencountry"
-> [js] update form/selectbox
EDIT: (code)
JS:
<script>
function BuildSelectbox(job,parent) {
try { req = window.XMLHttpRequest?new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { /* No AJAX Support */ }
req.open('get','subselects.php?job='+job+'&parent='+parent);
/* let the php echo the resultvalue */
req.onreadystatechange = function() {
handleResponse(div);
};
req.send(null);
}
function handleResponse(div) {
if ((req.readyState == 4) && (req.status == 200)) {
document.getElementById(job).value=req.responseText;
}
}
</script>
PHP part: (subselects.php)
<?
if ($_GET["job"]=="states") {
// assuming there is a key country in states
$state = "SELECT * FROM states where country=".$_GET["parent"];
$state = $pdo->prepare($state);
$state->execute();
} else {
// assuming there is a key state in cities
$city = "SELECT * FROM cities where state=".$_GET["parent"];
$citq = $pdo->prepare($city);
$citq->execute();
}
// echo the whole selectbox
echo '<select id="'.$_GET["job"].'">';
// put the option loop from your queryresult here
echo '</select>';
?>
HTML:
<div id="countries" onChange="BuildSelectbox('states',this.selectedIndex);>
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
</div>
<div id="states"></div>
<div id="cities"></div>
This dynamically generates full selectboxes and puts them into the empty divs "states and "cities". Of course you need to output the selectbox in the php code. Parent of states is country and parent of cities is states. Hope this explains it.
Please help a loafer. Am trying to populate a dropdown that is dependent on the first. The first is for state, when it is changed, the city should be populated. I have followed various tutorials online(some from stakeoverflow) and am stuck. I have very little knowledge of ajax and jquery. On top of that, am new to codeigniter. Below are my codes
Model for state
public function get_list(){
$this->db->from($this->table);
$result = $this->db->get();
$return = array();
if($result->num_rows() > 0) {
foreach($result->result_array() as $row) {
$return[$row['sid']] = $row['state'];
}
}
return $return;
}
Model for city
public function get_cities($state = null){
$this->db->select('ctid, city');
if($state != NULL){
$this->db->where('state_id', $state);
}
$query = $this->db->get($this->table);
$cities = array();
if($query->result()){
foreach ($query->result() as $cit) {
$cities[$cit->ctid] = $cit->city;
}
return $cities;
}else{
return FALSE;
}
}
My controller
public function index()
{
$data['state_option'] = $this->State_model->get_list();
$this->load->view('_parts/header');
$this->load->view('index', $data);
$this->load->view('_parts/footer');
}
public function dependent_dropdown($state)
{
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($this->city_model->get_cities($state)));
}
my jquery/ajax
$(document).ready(function(){
$('#state').change(function(){
// $("#city").html("<option>Loading...</option>");
$('#city > option').remove();
var state = $('#state').val();
if (state != "") {
$.ajax({
type: "POST",
data:'state',
url: "<?php echo site_url('site/dependent_dropdown'); ?>"+state,
success: function(data){
$.each(data, function(i, data){
$('#city').append("<option value='"+data.city+"'>"+data.city+"</option>");
});
}
});
}
else{
$('#city').html('<option>--Select City--</option>');
}
});
});
my view (state dropdown)
<select id="state" name="state" class="form-control" required>
<option value="" selected>--Select State--</option>
<?php foreach ($state_option as $state) { ?>
<option value="<?php echo $state ?>"><?php echo $state; ?></option>
<?php } ?>
</select>
(city dropdown)
<select id="city" name="city" class="form-control" required>
<option value="" selected>--Select City--</option>
</select>
I solved my problem eventually. I changed my view to display data for state like so
<select id="state" name="state" class="form-control" required>
<option value="" selected>--Select State--</option>
<?php foreach ($state_option as $state_id => $state) { ?>
<option id="state" value="<?php echo $state_id; ?>"><?php echo $state; ?></option>
<?php } ?>
</select>
Then I changed my ajax call like so
$(document).ready(function(){
$('#state').change(function(){
$('#city').html('<option>Loading....</option>');
var state = $('#state').val();
if (state != "") {
$.get("<?php echo base_url(); ?>site/dependent_dropdown/"+state).success(function(data){
$('#city > option').remove();
data = JSON.parse(data);
for(var i in data){
$('#city').append("<option value='"+i+"'>"+data[i]+"</option>");
}
})
}
else{
$('#city').html('<option>--Select City--</option>');
}
});
});
Check your Ajax request, change
url: "<?php echo site_url('site/dependent_dropdown'); ?>"+state,
To
url: "<?php echo base_url('site/dependent_dropdown'); ?>/"+state,
I have 3 select drop downs which I want when the first one selected, the second shows up, and when the second is selected, the third one shows up, by using if(isset($_post[first_one])) and for the third one using if(isset($_post[second_one]))
SQL:
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM sp_meeting_log ";
$result1 = $conn->query($sql);
PHP/HTML:
<div style="position:absolute; top:300px; left:500px;">
<form method="post">
<p>Choose:</p>
<!--Get all orgs ,forums ,Users data available for admin-->
//select the first
<select style="display:inline-block;" name="org">
<option value="All Orgs">All Orgs</option>
//first drop down info release
<?php
if ($result1->num_rows > 0) {
echo "<table><tr><th>orgID</th><th>orgName</th></tr>";
// output data of each row
while($row = $result1->fetch_assoc()) {
echo "<option>" .$row["orgID"]." /".$row["orgName"]."</option>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</select>
<select style="display:inline-block;" name="forum">
<option value="forum1"><h5>All Forums</h5></option>
<?php
// if the first dropdown post set
if(isset($_POST['org'])){
$result2 = $conn->query($sql);
if ($result2->num_rows > 0) {
echo "<table><tr><th>forumID</th><th>forumName</th></tr>";
// output data of each row
while($row = $result2->fetch_assoc()) {
echo "<option>".$row["forumID"]." / ".$row["forumName"]."</option>";
}
echo "</table>";
} else {
echo "0 results";
}
}
?>
</select>
//select the second
<select style="display:inline-block;" name="user">
<option><h5>All Users</h5></option>
<?php
// if the second drop down is set
if(isset($_POST['forum'])){
$result3 = $conn->query($sql);
if ($result3->num_rows > 0) {
echo "<table><tr><th>userID</th><th>username</th></tr>";
// output data of each row
while($row = $result3->fetch_assoc()) {
echo "<option>".$row["userID"]." / ".$row["username"]. "</option>";
}
echo "</table>";
} else {
echo "0 results";
}
}
?>
Essentially this is what the idea is. You want page one to just fetch from page two and post the result back to page one into the correct spots:
page1.php
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form>
<label>Org
<select id="org" name="org">
<option value="1">One</option>
<option value="2">Two</option>
</select>
</label>
<!-- This is where the forum html will drop into after ajax runs -->
<div id="forum"></div>
<!-- This is where the user html will drop into after ajax runs -->
<div id="user"></div>
</form>
<script type="text/javascript">
$(document).ready(function() {
// On change of a select menu
$(this).on('change','select',function(e){
// Assign selection
var thisSelect = $(this);
// Get the id name, this will tell page two
// what it's receiving
var sendType = thisSelect.attr('id');
// Get the actual value of the selection
var sendVal = thisSelect.val();
// Create essentially a POST
var sendData = { field: sendType, value: sendVal };
$.ajax({
// Send to page 2
url : '/page2.php',
// Use post method
type: "POST",
// Use post data from above
data : sendData,
// This is what will run on success
success:function(response){
// Parse the json coming back for placement
var jSon = JSON.parse(response);
// Save the correct html into the correct drop spot
$('#'+jSon.type).html(jSon.html);
},
error: function(response){
console.log(response);
}
});
});
});
</script>
page2.php
if(!empty($_POST)) {
$data = '';
ob_start();
if(isset($_POST['field'])) {
if($_POST['field'] == 'org') {
$type = 'forum';
?>
<label>Forum
<select id="forum" name="forum">
<option value="1">One</option>
<option value="2">Two</option>
</select>
</label>
<?php
}
elseif($_POST['field'] == 'forum') {
$type = 'user';
?>
<label>user
<select id="user" name="user">
<option value="1">One</option>
<option value="2">Two</option>
</select>
</label>
<?php }
$data = ob_get_contents();
ob_end_clean();
die(json_encode(array('type'=>$type,'html'=>$data)));
}
die(json_encode(array('type'=>'error','html'=>false)));
}
For some time I am battling to solve this problem but I am not coming to any conclusion so thought to seek some help here.
The problem is that I am getting a blank dropdown instead I should get list of cities populated from the database. Database connection is fine but I am not getting anything in my dropdown.
This is what I am doing:
<?php
require 'includes/connect.php'; - database connection
$country=$_REQUEST['country']; - get from form (index.php)
$q = "SELECT city FROM city where countryid=".$country;
$result = $mysqli->query($q) or die(mysqli_error($mysqli));
if ($result) {
?>
<select name="city">
<option>Select City</option>
$id = 0;
<?php while ($row = $result->fetch_object()) {
$src = $row->city;
$id = $id + 1;
?>
<option value= <?php $id ?> > <?php $src ?></option>
<?php } ?>
</select>
<?php } ?>
ajax script is this:
<script>
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{mlhttp=new XMLHttpRequest();}
catch(e) {
try{ xmlhttp= new ActiveXObject("Microsoft.XMLHTTP"); }
catch(e){ try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCity(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
This is my form code:
<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="150">Country</td>
<td width="150"><select name="country" onChange="getCity('findcity.php?country='+this.value)">
<option value="">Select Country</option>
<option value="1">New Zealand</option>
<option value="2">Canada</option>
</select></td>
</tr>
<tr style="">
<td>City</td>
<td ><div id="citydiv"><select name="city">
<option>Select City</option>
</select></div></td>
</tr>
</table>
</form>
I think the problem is where you are outputting the <option> tags.
Try using this block of code between your <select> tags.
<option>Select City</option>
<?php
$id = 0;
while ($row = $result->fetch_object()) {
$src = $row->city;
$id = $id + 1;
?>
<option value="<?php echo htmlspecialchars($id,ENT_QUOTES) ?>"><?php echo htmlspecialchars($src) ?></option>
<?php } ?>
Edit: To clarify, you didn't have any echo statements before the $id and $src variables. I added htmlspecialchars() as a habit to produce properly escaped html.
A few things to try:
If you request findcity.php manually in your browser with a city you know exist in the database, will i return the correct HTML?
Try with FireBug or another javascript debugger, to set a breakpoint in the onreadystatechange function and see if the returned values are as expected. Set the breakpoint at the first line of the function.
<input name="acname" type="text" id="acname" value="" maxlength="9">
Account Name </p>
<select name="src">
<option value="number"> :::: Select ::::</option>
<option value="did">DID</option>
<option value="tfn">TFN</option>
</select>
<span id="errmsg"></span> DID/TFN </p>
<select name="did" onchange='OnChange(this.form1.did);' >
<option value=""> :::: Select ::::</option>
<? $qry1 = mysql_query("SELECT * FROM ".NUMBERS." where Flag='1'") or die(mysql_error()) ;
while($res1 = mysql_fetch_array($qry1)) { ?>
<option value="<?=$res1['Numbers'] ?>"><?=$res1["Numbers"]?></option>
<? } ?>
</select>
SOURCE