How to change multiple dropdown values onchange by ajax? - ajax

I have created 4 dropdown of book levels, each one dependent on its upper level (ex. Book Level 2 shows dropdown values dependent on Book level 1 category and so on...) and it is working fine also, but now I want only Book Level 4 independent and should show the values if the Book Level 1 is not empty. i.e., onchange Book level 1, Book Level 2 dropdown shows the value dependent on Book level 1 category and it also should show the Book Level 4 dropdown values which are independent. Help is required.
index.php
<body>
<form method="post" name="AddBookDetails">
<table>
<tr>
<td>Book Level 1</td>
<td><select id="bl1" name="bookl1"><option value="" selected="selected">Book Level 1</option>
<?php
mysqli_set_charset($db,'utf8');
$result=mysqli_query($db,"select * from booklevel1 ORDER BY booklevel1 ASC");
if ($result>0){
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['bl1_code'].'">'.$row['booklevel1'].'</option>';
}
}
else{
echo '<option value="">Book Level 1 not present</option>';
}
?></select></td>
</tr>
<tr>
<td>Book Level 2</td>
<td><select id="bl2" name="bookl2" ><option value="" >Select Level 2</option></select></td>
</tr>
<tr>
<td>Book Level 3</td>
<td><select id="bl3" name="bookl3" ><option value="" >Select Level 3</option></select></td>
</tr>
<tr>
<td>Book Level 4</td>
<td><select id="bl4" name="bookl4" ><option value="" >Select Level 4</option></select></td>
</tr>
</table>
<input name="addbook" type="submit" value="Save">
</form>
</body>
ajaxData.php
<body>
<?php
include 'dbConfig.php';
if(!empty($_POST["bl1_code"])){
$query2=$_POST['bl1_code'];
$query = $db->query("SELECT * FROM booklevel2 WHERE bl1_code LIKE '%$query2%' ORDER BY booklevel2 ASC");
$rowCount = $query->num_rows;
//Book Level 2 option list
if($rowCount > 0){
echo '<option value="">Select Level 2</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['bl2_code'].'">'.$row['booklevel2'].'</option>';
}
}else{
echo '<option value="">Level 2 empty</option>';
}
}
elseif(!empty($_POST["bl2_code"])){
$query3=$_POST["bl2_code"];
$query = $db->query("SELECT * FROM booklevel3 WHERE bl2_code LIKE '%$query3%' ORDER BY booklevel3 ASC");
$rowCount = $query->num_rows;
//Book Level 3 option list
if($rowCount > 0){
echo '<option value="">Select Level 3</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['bl3_code'].'">'.$row['booklevel3'].'</option>';
}
}else{
echo '<option value="">Level 3 empty</option>';
}
}
elseif(!empty($_POST["bl3_code"])){
$query4=$_POST["bl3_code"];
$query = $db->query("SELECT * FROM booklevel4 WHERE bl3_code LIKE '%$query4%' ORDER BY booklevel4 ASC");
$rowCount = $query->num_rows;
//Book Level 4 option list
if($rowCount > 0){
echo '<option value="">Select Level 4</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['bl4_code'].'">'.$row['booklevel4'].'</option>';
}
}else{
echo '<option value="">Level 4 empty</option>';
}
}
?>
</body>
ajax.js
// JavaScript Document
$(document).ready(function() {
$('#bl1').on('change',function(){
var blevel1 = $(this).val();
if(blevel1){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'bl1_code='+blevel1,
success:function(html){
$('#bl2').html(html);
$('#bl3').html('<option value="">Select Level 2 First</option>');
$('#bl4').html('<option value="">Select Level 3 First</option>');
}
});
}else{
$('#bl2').html('<option value="">Select Level 1 First</option>');
$('#bl3').html('<option value="">Select Level 2 First</option>');
$('#bl4').html('<option value="">Select Level 3 First</option>');
}
});
$('#bl2').on('change',function(){
var blevel2 = $(this).val();
if(blevel2){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'bl2_code='+blevel2,
success:function(html){
$('#bl3').html(html);
}
});
}else{
$('#bl3').html('<option value="">Select Level 2 First</option>');
$('#bl4').html('<option value="">Select Level 3 First</option>');
}
});
$('#bl3').on('change',function(){
var blevel3 = $(this).val();
if(blevel3){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'bl3_code='+blevel3,
success:function(html){
$('#bl4').html(html);
}
});
}else{
$('#bl4').html('<option value="">Select Level 3 First</option>');
}
});
});

create bl1,bl2,bl3 bl4 function. on change call the function.
something like this
<select id="bl1" onchange="bl1()">
Just before bl1 function ends, call bl4();
function bl1()
{
$('#bl1').on('change',function(){
var blevel1 = $(this).val();
if(blevel1){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'bl1_code='+blevel1,
success:function(html){
$('#bl2').html(html);
$('#bl3').html('<option value="">Select Level 2 First</option>');
$('#bl4').html('<option value="">Select Level 3 First</option>');
}
});
}else{
$('#bl2').html('<option value="">Select Level 1 First</option>');
$('#bl3').html('<option value="">Select Level 2 First</option>');
$('#bl4').html('<option value="">Select Level 3 First</option>');
}
//function name here and business logic here
if(blah blah)
{
bl4();
}
else{ //blah blah}
}
}

Related

how to show selected dropdown in codeigniter using ajax

Problem is in my edit page the one dropdown value is selected but the other dropdown who called with first dropdown value is not show hear the code is
$(document).ready(function() {
// alert('onload');
// alert($('#company_name').val())
$('#company_name').change(function() {
var id = $('#company_name').val();
if (id != '') {
$.ajax({
url: BaseURL + 'admin/campaign/fetch_template',
type: 'POST',
data: {
id: id,
},
success: function(data) {
$('#template').html(data);
}
});
} else {
$('#template').html('<option value="selected">Select Template</option>');
}
});
});
I want to add this a selected value of dropdown.....
<select onchange='getTemplate(this.value);' class="form-control" id="template" name="template" data-placeholder="Select a option">
<option value="">Select Template</option>
</select>
this is the dropdown which i want to get selected value &
<select class="form-control" name="company" class="form-control " data-placeholder="Select a option" id="company_name">
<option value="1">Select Company</option>
<?php foreach ($company as $con) { ?>
<option value="<?php echo $con->company_id ?>" <?php echo $edit['id'] == $con->company_id ? 'selected' : '' ?>><?= $con->name; ?>
</option>
<?php } ?>
</select>
and this is where i call a company name to select the templeate each company

Populate dynamic dropdown, Codeigniter

I'm trying to make a dynamic dropdown with Codeigniter but I'm having trouble getting the values on the next dropdown. When I select and option on the first dropdown, the second dropdown is not populated:
I'm also not familiar at using AJAX, I only write the script based on what I searched so please teach me what to do to make the dynamic dropdown work.
This is my Model:
public function category()
{
$this->db->order_by("category", "ASC");
$query = $this->db->get('categories');
return $query->result();
}
function get_subcategory($parent_id)
{
$this->db->where('parent_id', $parent_id);
$this->db->order_by('sub_category', 'ASC');
$query = $this->db->get('sub_categories');
$output = '<option value="">Select Sub-Category</option>';
foreach ($query->result() as $row) {
$output .= '<option value="' . $row['id'] . '">' . $row['sub_category'] . '</option>';
}
return $output;
}
My Controller:
public function category()
{
$data['title'] = 'List of Category';
$this->load->view('../admin/template/admin_header');
$this->load->view('../admin/template/admin_topnav');
$this->load->view('../admin/template/admin_sidebar');
$this->load->view('../admin/category/category', $data);
$this->load->view('../admin/template/admin_footer');
}
function get_subcategory()
{
if ($this->input->post('parent_id')) {
echo $this->Admin_model->get_subcategory($this->input->post('parent_id'));
}
}
View:
<div class="form-group">
<label for="" class="control-label">Category</label>
<select name="category" id="category" class="custom-select select2" required>
<option value="">- Select Category -</option>
<?php
foreach ($category as $row) {
echo '<option value="' . $row->id. '">' . $row->category . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="" class="control-label">Sub Category</label>
<select name="sub_category" id="sub_category_id" class="custom-select select2" required>
<option value="">- Select Sub Category -</option>
</select>
</div>
And script:
$(document).ready(function() {
$('#category').change(function() {
var parent_id = $('#category').val();
if (parent_id != '') {
$.ajax({
url: "<?php echo base_url(); ?>admin/get_subcategory",
method: "POST",
data: {parent_id:parent_id},
success: function(data) {
$('#sub_category_id').html(data);
}
});
} else {
$('#sub_category_id').html('<option value="">Select Sub Category</option>');
}
});
});
Your question doesn't mention it, but your CSS suggests your selects are actually using Select2. When you initialise a select as a Select2, it makes a copy of the initial HTML, and adds styling and JS to it, and it is the copy that you see and interact with. The original HTML is no longer visible or used at all.
So if you later come along and modify that original HTML, it will have no effect on the Select2 you already generated and can see an interact with on the page.
One solution is to reinitialise that Select2 after you modify it.
UPDATE
I've added a working snippet, with some hard-coded HTML to simulate what your AJAX returns. Click run to try it.
$(document).ready(function () {
// Initialise Select2s
$('.select2').select2();
// Fake HTML, simulate what your AJAX returns
let fakedHTMLResponse = '<option value="water">Water</option><option value="juice">Juice</option><option value="beer">Beer</option>';
$('#category').change(function () {
var parent_id = $('#category').val();
// console.log('parent_id', parent_id);
if (parent_id != '') {
// Your AJAX call happens here, let's simulate the success
// response it gets back, and handle it the same way.
$('#sub_category_id').select2('destroy')
.html(fakedHTMLResponse)
.select2();
} else {
$('#sub_category_id').html('<option value="">Select Sub Category</option>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<select id="category" class="select2" name="food">
<option value="">- Select Category -</option>
<option value="fruits">Fruits</option>
<option value="vegetables">Vegetables</option>
<option value="cakes">Cakes</option>
</select>
<select id="sub_category_id" class="select2" name="drink">
<option value="">- Select Sub Category -</option>
</select>
Note:
Convention is to use GET when retrieving data, and POST for changing data. Your AJAX calls are just retrieving data to display, so really should be GET;
If you are going to use a jQuery selector more than once, it makes sense to cache them. Eg in the above code you should do something like:
let $category = $('#category');
let $sub = $('#sub_category_id');
// And then every time you need to use that selectors, use the variable, eg:
$category.select2();
$category.change(function ...
$sub.select2('destroy');
// etc
In your success response write this and remove the else from down there.
success: function(data) {
$('#sub_category_id').append('<option value=>Select Sub Category</option>');
for (var i=0; i<data.length; i++) {
$('#sub_category_id').append($('<option>', {
value: data[i].id,
text : data[i].sub_category
}));
}
}
get AJAX response in the array from your controller and then run this through javascript like this.
id is id from your db
and sub_category is sub_category coming from your db
with ajax response array.

Creating a cascade drop down without primary and foriegn key relationship with coeigniter

This is the structure of my table "task"
projectname
employee
clientname
task
Dependencies are as follows
One project has multiple task
One project has multiple employees
I need to create a dropdown list when user selects a particular project tasks relevant to them will automatically load to the next dropdown list. In this situation I do not need primary and foriegn key relationship. Any help would be really appreciated
This is my controller
public function Task(){
$data['cname'] = $this->welcome4->show_students3();
$data['projects'] = $this->welcome4->show_students();
$data['employee'] = $this->welcome4->show_students2();
$this->load->view('template/navigation');
$this->load->view('template/sideNav');
$this->load->view('template/header');
$this->load->view('Task',$data);
$this->load->view('template/footer');
}
This is my model
function show_students2(){
$query = $this->db->get('employee');
$query_result = $query->result();
return $query_result;
}
function show_students3(){
$query = $this->db->get('clientdetails');
$query_result = $query->result();
return $query_result;
}
function show_students4(){
$query = $this->db->get('task');
$query_result = $query->result();
return $query_result;
}
This is my view
<div class="form-group">
<label>Select Project</label>
</div>
<div class="form-group">
<select name="projectname" class="input form-control">
<option value="none" selected="selected">Select Project</option>
<?php foreach($projects as $s):?>
<option value="<?php echo $s->projectname?>"><?php echo $s->projectname?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label>Select Client</label>
<select name="cname" class="input form-control">
<option value="none" selected="selected">Select client</option>
<?php foreach($cname as $s):?>
<option value="<?php echo $s->cname?>"><?php echo $s->cname?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label>Select Employee</label>
</div>
<div class="form-group">
<select name="employee" class="input form-control">
<option value="none" selected="selected">Select Employee</option>
<?php foreach($employee as $s):?>
<option value="<?php echo $s->employee?>"><?php echo $s->employee?></option>
<?php endforeach;?>
</select>
</div>
This loads all projects, clients, employee in the database.But now I want when project is selected in the first drodown, second dropdown should show only relevant clients and employees to it. Not all of them
Lets consider this will be your Projects select box, in which you are loading data dynamically on page load with php.
<select name="projectname" id="projectname"></select>
Tasks select box.
<select name="tasks" id="tasks"></select>
Inside your controller add below mentioned code. This function will be used for get data from ajax call.
public function getTasks() {
$Id = $this->input->post('project_id');
if ($Id):
$this->load->model('Task_model', 'Tasks', TRUE);
$data = $this->Tasks->getProjectTasks($Id);
if ($data):
$result['status'] = true;
$result['records'] = $data;
endif;
else:
$result['status'] = false;
endif;
echo json_encode($fdata);
}
Inside model please add this function. Which will fetch data from DB
ans pass it to controller back.
public function getProjectTasks($id = null) {
if ($id):
$this->db->select('id,task');
$this->db->where('project_id', $id);
$this->db->where('status', TRUE);
$query = $this->db->get('tasks');
$records = $query->result();
if ($records):
return $records;
else:
return false;
endif;
else:
return false;
endif;
}
And finally in you View file please add below function.
$(document).on('#projectname', 'change', function() {
var projectId = $(this).val();
$.ajax({
type: 'POST',
url: 'URL',
data: {project_id: projectId},
dataType: "json",
beforeSend: function() {
$('#tasks')
.empty()
.append('<option selected="selected">Select Task</option>');
},
success: function(data) {
if (data.status) {
$.each(data.records, function(i, item) {
$('#tasks').append($('<option>', {
value: item.value,
text: item.text
}
));
});
} else {
$('#tasks')
.empty()
.append('<option selected="selected">No Task available</option>');
}
}
});
});

Data does not display after navigate page

i'm having problem. i have a survey form, in this form i used also the ajax to call some of the data. when user click cancel, i want it to navigate to other page where it display the list of data in listview using ajax. for the clicking and navigation part, i've succeed to bring it to the page that i want, but the problem is, it does not display anymore the list of data. I used the same way as i did for other page but for this i can't get..any help? i've gone through my code several times but i can't get what makes it wrong. this is my code for the page survey form:
$('#MrateCourse').live('pageinit', function(){
var rowInput = "1";
var pageInput = "1";
var idInput = "${courseId}";
var regNoInput = "${regNo}";
$.ajax({
url: '${pageContext.request.contextPath}/getRegisteredClassesDetails.html',
data: ( {rows: rowInput, page: pageInput, courseId: idInput, regNo: regNoInput}),
type: 'POST',
success: function(json_results){
$('#list').append('<ul></ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(courseId) {
html = ' Course Name :
+ '<b>' + json_results.rows[courseId].courseName + '</b>';
html += '</br> Registered Person :
+ '<b>' + json_results.rows[courseId].fullName + '</b>';
listItems.append(html);
});
$('#list ul').listview();
}
});
});
$(function() {
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
if(day<10){
day='0'+day;
}
if(month<10){
month='0'+month;
}
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
if (minutes < 10)
minutes = "0" + minutes;
$('#dateTime').html("<b>" + month + "/" + day + "/" + year + " " + hours + ":" + minutes + " " + suffix + "</b>");
});
<form id="" action="${pageContext.request.contextPath}/MRegisteredClasses.phone" method="POST">
<table>
<tr>
<td>Date:
<span id="dateTime"></span><br/></td>
</tr>
<tr>
<td>Company:</td>
<td><input type="text" value=""/><br/></td>
</tr>
<tr>
<td><b>Based on your experience in this course, please answer<br>the following questions:
<br>1 = Strongly Disagree, 5 = Strongly Agree</b></td>
</tr>
<tr>
<td>The web-based training media used was of high quality.</td>
<td><select>
<option value=""></option>
<option value="5">5</option>
<option value="5">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br/></td>
</tr>
<tr>
<td>I had enough time to learn the subject matter covered in the course.</td>
<td><select>
<option value=""></option>
<option value="5">5</option>
<option value="5">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br/></td>
</tr>
<tr>
<td>My knowledge and/or skills increased as a result of this course.</td>
<td><select>
<option value=""></option>
<option value="5">5</option>
<option value="5">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br/></td>
</tr>
<tr>
<td>Additional comments or ideas to improve this course:</td>
</tr>
<tr>
<td><textarea rows="3" ></textarea></td>
</tr>
<tr>
<td>What additional topics would you like to see addressed in a future online course?</td>
</tr>
<tr>
<td><textarea rows="3"></textarea></td>
</tr>
<tr>
<td align="left">
<input type="submit" data-inline="true" id="submit" value="Submit This Survey" class="ui-btn-right"
onClick="confirm( 'Thanks for filling the survey' )"/>
<a href="${pageContext.request.contextPath}/MRegisteredClasses.phone" class="ui-btn-right"
data-role="button" data-inline="true">Cancel</a>
</td>
</tr>
</table>
</form>
and this is my code for the page that it need to navigate.
<div data-role="page" id="MregisteredClasses">
<div data-role="content">
<h3>Courses Name</h3>
<p id="note">*Click at the courses to view the details</p>
<h1></h1>
<div id="courseName">
<ul data-role="listview" data-inset="true" id="list"></ul>
<script type="text/javascript">
$('#MregisteredClasses').on('pageinit', function(){
var rowInput = "1";
var pageInput = "1";
$.ajax({
url: '${pageContext.request.contextPath}/getRegisteredClassesData.html',
data: ( {rows : rowInput , page : pageInput}),
type: 'POST',
success: function(json_results){
$('#list').append('<ul data-role="listview" data-inset="true" data-split-icon="gear"</ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(key) {
html = '<li <h3><a href="${pageContext.request.contextPath}/MRegisteredClassesDetail.phone?courseId='
+ [json_results.rows[key].courseId] + '&regNo=' + [json_results.rows[key].regNo] +
'"rel="external">' + json_results.rows[key].courseName+ '</a></h3>'
+ '<a href="${pageContext.request.contextPath}/MRateCourse.phone?courseId='
+ [json_results.rows[key].courseId] + '&regNo=' + [json_results.rows[key].regNo] +
'"rel="external">RATE THIS COURSE</a>';
listItems.append(html);
});
$('#list ul').listview();
},
});
});
</script>
</div>
</div><!-- /content -->
I got it already.. I add data-ajax="false" to my form.

How to use AJAX to populate state list depending on Country list?

I have the code below that will change a state dropdown list when you change the country list.
How can I make it change the state list ONLY when country ID number 234 and 224 are selected?
If another country is selected it should be change into this text input box
<input type="text" name="othstate" value="" class="textBox">
The form
<form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
The javascript
<script>
function getState(countryId)
{
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Just check the countryId value before you do the AJAX request and only perform the request if the countryId is in the allowable range. In the case where the countryId doesn't match, I would hide the select (probably clear it's value, too) and show an already existing input that was previously hidden. The reverse should be done if an allowable country is chosen.
jQuery example below:
<form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
<input type="text" name="othstate" value="" class="textBox" style="display: none;">
</form>
$(function() {
$('#country').change( function() {
var val = $(this).val();
if (val == 223 || val == 224) {
$('#othstate').val('').hide();
$.ajax({
url: 'findState.php',
dataType: 'html',
data: { country : val },
success: function(data) {
$('#state').html( data );
}
});
}
else {
$('#state').val('').hide();
$('#othstate').show();
}
});
});
I think the simple thing to do is to provide a state dropdown and a text entry box with different ids. Set the display of both to none and then you just need to surround your contents of getState() with
if (countryId == 233 || countryId == 234) {
/* Ajax state population here */
dropdownId.display = 'block';
textEntryId.display = 'none';
}
else {
textEntryId.display = 'block';
dropdownId.display = 'none';
}
(where dropdownId and textEntryId are the ids of the relevant UI components) so you enable/display the display for the state dropdown or the text entry upon selection.
JQuery is all well and good, but I wouldn't introduce it just to solve this problem.
EDIT: here is a solution that works quite well for the task, adapting the lines of Tvanfosson:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script>
$(function() {
$('#country').change( function() {
var val = $(this).val();
if (val == 223 || val == 224) {
$('#othstate').val('').hide();
$.ajax({
url: 'findState.php',
dataType: 'html',
data: { country : val },
success: function(data) {
$('#state').html( data );
}
});
}
else {
$('#state').val('').hide();
$('#othstate').show();
}
});
});
</script>
<select style="background-color: #ffffa0" name="country" id=country >
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
<input type="text" name="othstate" id=othstate value="" class="textBox" style="display: none;">
As you can see, I eliminated the <form> element which is not absolutely necessary but can be added (and then has to be used properly in case JS is deactivated at the users end. See
here.
I also eliminated the onchange event which is being replaced by the 'change()` jquery function.
**index.html**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Populate City Dropdown Using jQuery Ajax</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "ajaxServer.jsp",
data: { country : selectedCountry }
}).done(function(data){
$("#response").html(data);
});
});
});
</script>
<style>
select { width: 10em }
</style>
</head>
<body>
<form>
<table>
<tr>
<td> <label>Country:</label></td>
<td> <select class="country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
</select>
</td>
</tr>
<tr><td >
<label>States:</label></td>
<td> <select id="response">
<option>Select State</option>
</select>
</td></tr>
</table>
</form>
</body>
</html>
**ajaxServer.jsp**
<option>Select State</option>
<%
String count=request.getParameter("country");
String india[]={"Mumbai", "New Delhi", "Bangalore"};
String usa[]={"New Yourk", "Los Angeles","California"};
String uk[]={"London", "Manchester", "Liverpool"};
String states[];
if(count.equals("india"))
{
for(int i=0;i<=2;i++)
{
out.print("<option>"+india[i]+"</option>");
}
}
else if(count.equals("usa"))
{
for(int i=0;i<usa.length;i++)
{
out.print("<option>"+usa[i]+"</option>");
}
}
else if(count.equals("uk"))
{
for(int i=0;i<=2;i++)
{
out.print("<option>"+uk[i]+"</option>");
}
}
%>
VK API just select country , get it id and select city from
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
var _getCountry = function() {
$j.ajax({
url: "http://api.vk.com/method/database.getCountries",
data: {
'v': 5.5,
'need_all': 0,
'code' : 'RU,UA,BY,KZ,KG,LV,EE'
// 'count': 10
},
dataType: 'jsonp',
success: function(data, status) {
if (status !== 'success') {
return false;
}
console.log(data.response, status);
$j.each(data.response.items, function(i, item) {
console.log("each country");
var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
country_options.push(newOption);
});
document.getElementById('countrylist').innerHTML = country_options;
}
});
}
var _getCity = function(country_id) {
$j.ajax({
url: "http://api.vk.com/method/database.getCities",
data: {
'v': 5.61,
'need_all': 0,
'country_id': country_id
},
dataType: 'jsonp',
success: function(data, status) {
if (status !== 'success') {
return false;
}
console.log(data.response, status);
$j.each(data.response.items, function(i, item) {
console.log("each city");
var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
city_options.push(newOption);
});
document.getElementById('citylist').innerHTML = city_options;
}
});
}
var city_options = [];
var country_options = [];
$j(document).ready(function () {
_getCountry();
$j('#country').on('input',function() {
var opt = $j('option[value="'+$j(this).val()+'"]');
var countryid = opt.attr('id');
_getCity(countryid);
});
});
</script>
<div class="form-group">
<label class="col-lg-4 control-label">Страна:</label>
<div class="col-lg-8">
<div class="controls">
<input name="country" list="countrylist" id="country" class="form-control" />
<datalist id="countrylist">
</datalist>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label">Город:</label>
<div class="col-lg-8">
<input name="city" list="citylist" id="city" class="form-control"/>
<datalist id="citylist">
</datalist>
</div>
</div>
////////////////// connection file con.php rishabh
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db( 'testajax' );
?>
/////////////////////////// index.php rishabh
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<?php
include('con.php');
?>
<form>
<div class="frmDronpDown">
<div class="row">
<table><tr><td><label>Country:</label><br/>
<select name="country" id="country" data-name="country" class="demoInputBox" onChange="getCountry(this.value);">
<option value="">Select Country</option>
<?php
$sql = mysql_query("SELECT distinct country FROM statecont ");
while($result=mysql_fetch_array($sql)){
?>
<option value="<?php echo $result['country']; ?>"><?php echo $result['country']; ?></option>
<?php
}
?>
</select> </td>
<td>
<label>Phone:</label><br/>
<select name="phone" id="phone" data-name="phone" class="demoInputBox" onChange="getPhone(this.value);">
<option value="">Select Country</option>
<?php
$sql = mysql_query("SELECT distinct phone FROM statecont ");
while($result=mysql_fetch_array($sql)){
?>
<option value="<?php echo $result['phone']; ?>"><?php echo $result['phone']; ?></option>
<?php
}
?>
</select>
</td></tr></table>
</div>
<div id="state-list"></div>
</div>
</form>
<script>
function getCountry(val) {
var dataname = $('#country').attr('data-name');
console.log(dataname);
$.ajax({
type: "POST",
url: "data.php",
data: {
value_name: val,
colomn_name: dataname
},
success: function (data){
$("#state-list").html(data);
}
});
}
function getPhone(val) {
var dataname = $('#phone').attr('data-name');
console.log(dataname);
$.ajax({
type: "POST",
url: "data.php",
data: {
value_name: val,
colomn_name: dataname
},
success: function (data){
$("#state-list").html(data);
}
});
}
</script>
// ////////////////////data file data.php rishabh
<?php
$val = $_POST["value_name"];
$colomn = $_POST["colomn_name"];
include('con.php');
$sql_aa = mysql_query("SELECT * FROM statecont where ".$colomn."='$val'"); ?>
<table>
<tr><td>State</td><td>Countery</td></tr>
<?php while($result_aa=mysql_fetch_array($sql_aa)){ ?>
<tr><td><?php echo $result_aa['state']; ?></td><td><?php echo $result_aa['country']; ?></td></tr>
<?php } ?>
</table>

Resources