JSP Ajax populate drop down list based on the selected value - ajax

I have a drop down list will retrieve all product category from database and populate, another drop down list will show the product name based on the category selected by user.I am able to populate category but I was stuck at the product part
<p>
<label for="pcategory">Product Category</label>
<select name="pcategory" size="0" onchange="get_product(this.selectedIndex);">
<%
Category cat = new Category();
java.util.ArrayList<Category> catList = cat.retrieveCategory();
for (int i = 0; i < catList.size(); i++) {
%>
<option value="<%=(i + 1)%>"><%=catList.get(i).getCatname()%></option>
<%
}
%>
</select>
</p>
<jsp:include page="data.jsp"/>
function get_product(category){
$.ajax({
type: "GET",
url: "data.jsp",
data: "category=" + category,
success: function(msg){
}
});
}
This is for data.jsp
<p>
<label for="pname">Product Name:</label>
<select name="state" id="state">
<%
if (request.getParameter("category") != null) {
%>
<option value="1">1</option>
<option value="2">2</option>
<% } else {
%>
<option value="1">2</option>
<option value="2">3</option>
<% }%>
</select>
my data.jsp will populate the product name. By default will populate the first category from database if user never change the category drop down list.

I was able to do the following simple example using a servlet to get product names based on a product category. You'll need to modify it a little bit to fit into your particular scenario. Let me know if this is helpful and puts you down the right path...
The HTML page:
<html>
<head>
<SCRIPT SRC="jquery.js" TYPE="text/javascript"></SCRIPT>
</head>
<body>
<p>
<label for="pcategory">Product Category</label>
<select name="pcategory" id="pcategory" size="0">
<option value="1">Category 1</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
</p>
<p>
<label for="pname">Product Name:</label>
<select name="state" id="state">
<option value="1">Product Name 1 For Category 1</option>
<option value="2">Product Name 2 For Category 1</option>
<option value="3">Product Name 3 For Category 1</option>
</select>
</p>
</body>
<script type="text/javascript">
$category = $('#pcategory');
$category.change (
function() {
$.ajax({
type: "GET",
url: "GetProductName",
data: {category: $category.attr("selectedIndex") },
success: function(data){
$("#state").html(data)
}
});
}
);
</script>
</html>
The servlet which will give you the product names...
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class GetProductName extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
int category = Integer.parseInt(request.getParameter("category"));
switch (category) {
case 1:
out.print(
"<option value='1'>Product Name 1 For Category 2</option>" +
"<option value='2'>Product Name 2 For Category 2</option>" +
"<option value='3'>Product Name 3 For Category 2</option>"
);
break;
case 2:
out.print(
"<option value='1'>Product Name 1 For Category 3</option>" +
"<option value='2'>Product Name 2 For Category 3</option>" +
"<option value='3'>Product Name 3 For Category 3</option>"
);
break;
default:
out.print(
"<option value='1'>Product Name 1 For Category 1</option>" +
"<option value='2'>Product Name 2 For Category 1</option>" +
"<option value='3'>Product Name 3 For Category 1</option>"
);
break;
}
} catch (Exception ex) {
out.print("Error getting product name..." + ex.toString());
}
finally {
out.close();
}
}
}

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.

How to send Array from Select List to ajax

I'm new to Ajax and I can't find any way to pass my data Properly, my Sub-Category is dependent on categories output, my problem now is that when I select 2 or more item in category, the output of Sub-Category don't pile up on each other.
I know I have to put my category on array but I don't know how it will work if the data come on select list.
My Filter
<div class="col-lg-3 col-md-3 col-sm-3">
<select id="assignedCategory" class="form-control selectpicker" title="Category" value="#ViewBag.AssignedCategory" asp-items="#ApplicationCategory" multiple asp-for="#category" onchange="GetSubCat();">
</select>
</div>
<div class="col-lg-3 col-md-3 col-sm-3">
<select id="assignedSubCategory" class="form-control selectpicker" title="Sub-Catergory" multiple>
</select>
</div>
Ajax
function GetSubCat() {
$('#assignedSubCategory').html('');
$.ajax({
url: '#Url.Action("GetSubCat")',
type: 'post',
dataType: 'json',
data: {
CatId: $('#assignedCategory option:selected').val() <!--This Part Right Here, I don't know how to make this an Array.-->
},
success: (data) => {
$.each(data, (i, e) => {
var elem = '<option value="' + e.value + '">' + e.text + '</option>'
$('#assignedSubCategory').append(elem);
$('#assignedSubCategory').selectpicker('refresh');
});
}
});
}
Controller
[HttpPost]
[AllowAnonymous]
public JsonResult GetSubCat(int?[] CatId)
{
var getCat = db.Subcategories.FromSqlRaw($#"
select sc.* from CRM_Subcategories sc
left join CRM_Categories c on sc.CategoryId = c.Id
where c.Id IN ({CatId})").Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Value
}).ToList();
return Json(getCat);
}
1.You could get selected array like below:
$('#assignedCategory').val();
2.Upon you select an option in selectlist, the onchange event will be triggered. That is to say if you select multiple options, it will trigger GetSubCat function for multiple times and post to backend for multiple times. If you do not care with this. Just change ajax post data to: $('#assignedCategory').val();.
3.You use selectpicker in your code, it seems you use Bootstrap-select plugin in your project. Bootstrap-select exposes a few events for hooking into select functionality. I think you could use hidden.bs.select event to post your selected array list to backend. This event is fired when the dropdown has finished being hidden from the user. That is to say it will trigger ajax upon the select menu closed.
Here is a working sample:
<div class="col-lg-3 col-md-3 col-sm-3" id="category"> //add id here...
<select id="assignedCategory" class="form-control selectpicker" title="Category" value="#ViewBag.AssignedCategory" multiple >
<option value="1">aa</option>
<option value="2">bb</option>
<option value="3">cc</option>
</select>
</div>
<div class="col-lg-3 col-md-3 col-sm-3">
<select id="assignedSubCategory" class="form-control selectpicker" title="Sub-Catergory" multiple>
</select>
</div>
#section Scripts
{
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/css/bootstrap-select.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/js/bootstrap-select.min.js"></script>
<script>
$('#category').on('hide.bs.select', function (e) {
$.ajax({
url: '#Url.Action("GetSubCat")',
type: 'post',
dataType: 'json',
data: {
CatId: $('#assignedCategory').val()
},
success: (data) => {
$.each(data, (i, e) => {
var elem = '<option value="' + e.value + '">' + e.text + '</option>'
$('#assignedSubCategory').append(elem);
$('#assignedSubCategory').selectpicker('refresh');
});
}
});
});
</script>
}

How to get auto response value by using Two Drop-Down List in PHP & Ajax?

How to get the final value in AJAX using two drop-down value,
Koluextension.php
<html>
<head>
<title> Upgrade Cost</title>
</head>
<form method='POST' action='upgradecost.php'>
Name : <input type="text" name="name"/><br/><br/>
Email Id : <input type="text" name="email_id"/><br/><br/>
Contact Number : <input type="text" name="contact_number"/><br/><br/>
I have :
<select onchange="getvalue()" id="old">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select><br/><br/>
I want :
<select onchange="getvalue()" id="new">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select>
</form>
</html>
upgratedcost.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if(isset($_POST['old']) && isset($_POST['new'])){
$old = $_POST['old'];
$new = $_POST['new'];
if($old=='one'&&$new=='two'){
echo json_encode(array('sucess'=>'sucess','msg'=>'10$'));
}
else{echo json_encode(array('sucess'=>'sucess','msg'=>'0'));}
} ?>
calculatecost.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if(isset($_POST['old']) && isset($_POST['new'])){
$old = $_POST['old'];
$new = $_POST['new'];
if($old=='one'&&$new=='two'){
echo json_encode(array('sucess'=>'sucess','msg'=>'10$'));
}
else{echo json_encode(array('sucess'=>'sucess','msg'=>'0'));}
} ?>
Expected Output:
If customer choose: I have -> one and I want -> two the cost should
be $10 as an Auto response to show to the customer. [Every combination has its own cost]
I have done some changes to your code. And add some Ajax to this and also created separate PHP code, you can get basic idea using this code example.
Html page -
<html>
<head>
<title> Upgrade Cost</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<form method='POST' action='upgradecost.php'>
Name : <input type="text" name="name"/><br/><br/>
Email Id : <input type="text" name="email_id"/><br/><br/>
Contact Number : <input type="text" name="contact_number"/><br/><br/>
I have :
<select id="old">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select><br/><br/>
I want :
<select id="new">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select>
</form>
<button id="btn_check_value">Check for value</button>
<script>
$(document).ready(function(){
$('#btn_check_value').on('click',function(){
var old_val = $("#old option:selected").val();
var new_val = $("#new option:selected").val();
$.ajax({
method: "POST",
url: "value_calculate.php",
data: { old: old_val, new: new_val }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
})
})
</script>
</html>
PHP page code -
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if(isset($_POST['old']) && isset($_POST['new'])){
$old = $_POST['old'];
$new = $_POST['new'];
if($old=='one'&&$new=='two'){echo json_encode(array('sucess'=>'sucess','msg'=>'10$'));}else{echo json_encode(array('sucess'=>'sucess','msg'=>'0'));}
} ?>
Here what happen is, once user do the selections user have to click the "Check for value" button and once user click on that button it'll make Ajax request to PHP page "value_calculate.php" and php code return value according to user selection.
This is not complete solution but you can get basic idea and improve this code according to you.
Thanks,
Tharanga.
You can try this solution:
1) Modify Your HTML like this:
<html>
<head>
<title> Upgrade Cost</title>
</head>
<form method='POST' action='upgradecost.php'>
Name : <input type="text" name="name"/><br/><br/>
Email Id : <input type="text" name="email_id"/><br/><br/>
Contact Number : <input type="text" name="contact_number"/><br/><br/>
I have :
<select onchange="getvalue()" id="old">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select><br/><br/>
I want :
<select onchange="getvalue()" id="new">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select>
</form>
</html>
2) Add this JavaScript function to your page:
function getValue() {
var cost1=$('#old').val();
var cost2=$('#new').val();
$.ajax({
url: '{{ url("calculateCost.php") }}',
type: 'get',
//async:true,
data: {
oldId: cost1,
NewId: cost2,
},
dataType: 'json',
success: function(json) {
//you can calculate total cost on server and show updated cost using
//jquery anywhere on your form
//do whatever you wanted to do
//you can easily manipulate DOM using jQuery
},
error : function(xhr, textStatus, errorThrown ) {
//in case ajax call error
}
});
}
}
}
Haven't tested this code. Please make necessary changes. If you still don't know what is going on then I would recommend you to go through a detailed tutorial in order to understand the concepts first and then code. e.g. https://www.w3schools.com/php/php_ajax_intro.asp
Issues (based from your post in daniweb website):
There is no input field with an id of est_shi_val
Looking at your code, you want to use both the old and new select fields, when changed will put the result to a hidden input field. But the result will only return if both the old and new have selected options. Is this what you want? Or at least one of them should be selected, and the result will return?
Use a database to look-up for conditions instead of manually creating if-else conditions
Instructions:
You may remove first your onchange attribute/call in your old and new select fields.
AJAX Call:
$("#old, #new").change(function(){ /* WHEN YOU CHANGE THE VALUE OF THE OLD OR NEW INPUT FIELD */
var old = $("#old").val(),
newval = $("#new").val();
$.ajax({ /* TRIGGER THE AJAX CALL */
type: "POST", /* TYPE OF METHOD TO USE TO PASS THE DATA */
url: "ajax_ship_data.php", /* PAGE WHERE WE WILL PASS THE DATA */
data: {'old':old, 'new':newval}, /* THE DATA WE WILL BE PASSING */
dataType: 'json',
success: function(result){ /* GET THE RETURNED DATA */
$("#results").html(result.message); /* THE RETURNED MESSAGE WILL BE SHOWN IN THIS DIV, PROVIDED THAT YOU HAVE A DIV WITH AN ID OF "results" */
$('#shipping_weight').val(result.weight); /* ASSUMING THAT YOU HAVE A HIDDEN INPUT FIELD WITH AN ID OF "shipping_weight" */
}
});
});
Then at your ajax_ship_data.php:
$shipping_weight = 0;
$message = 'Please select an option from both fields.';
if(isset($_POST['old']) && isset($_POST['new'])){
$old = $_POST['old'];
$new = $_POST['new'];
//part 1
if($old == 'three_compact' && $new == 'five_compact'){
$shipping_weight = 10;
$message = 'Shipping weight is 10.';
}
/** REST OF IF-ELSE CONDITIONS **/
}
echo json_encode(array('message' => $message, 'weight' => $shipping_weight));
Other Option: No AJAX
You may also do this without using AJAX since you're manually creating conditions:
$("#old, #new").change(function(){
var old = $("#old").val(),
newval = $("#new").val();
if(old=='three_compact' && newval=='five_compact'){
$("#results").text('10');
}
/* REST OF IF-ELSE CONDITIONS */
});
Take a look at this fiddle.

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