How to create drop down - ajax

I want to generate a list on items in a drop down based on a previous choice from another select. All items ar in the database.
Here is what I did:
Javascript:
$(document).ready(function () {
$(document).on('change', '#province_name', function() {
var province_id = $(this).val();
var div = $(this).parent();
var op = " ";
$.ajax({
type: 'get',
url: '{!!URL::to('admin/findIDProvince')!!}',
data: {'id':province_id},
success: function(data){
for (var i = 0; i < data.length; i++){
op += '<option value="'+data[i].id+'">'+data[i].city_name+'</option>';
}
div.find('#city').html(" ");
div.find('#city').append(op);
},
error: function(){
console.log('success');
},
});
});
});
Routes (web.php):
Route::namespace('Admin')->prefix('admin')->middleware('auth', 'CheckAdmin')->group(function (){
$this->get('/findIDProvince', 'SchoolsListController#findIDProvince');
});
Controller (Admin/SchoolsListController.php):
public function findIDProvince(Request $request)
{
$data = City::select('name', 'id')->where('province_id', $request->id)->take(100)->get();
return response()->json($data);
}
HTML (view.blade.php)
<div class="form-group">
<label class="col-md-3" for="province_name">province_name</label>
<div class="col-md-9">
<select id="province_name" name="province_name" class="form-control col-md-12" required>
#foreach($province_names as $province_name)
<option value="{{ $province_name->id }}">{{ $province_name->province_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3" for="city_name">city_name</label>
<div class="col-md-9">
<select id="city_name" name="city_name" class="form-control col-md-12" required>
</select>
</div>
</div>
What am I doing wrong?

First, create a hidden filed with the value for which the option that need to be selected.
<input type="hidden" value="{{ $yourOptionValueToSelect }}" id="selectThis">
Then with jQuery find the matching value from your option and change the corresponding attribute as selected.
$('option').each(function() {
if (this.value == $('#selectThis').val()) {
this.setAttribute('selected', 'selected');
}
});
Example:
<input type="hidden" value="2" id="selectThis">
<select>
<option value="1">Hello</option>
<option value="2">World</option>
</select>
Here Option 2 will be selected by default with the above jQuery Code.
In your view it will be changed to:
<option value="2" selected="selected">World</option>

// prepend : attach default value to the begining of the dropdown for region
// $('.region').prepend('<option value="default" selected="selected">Please select</option>');
$('.region').on('change', function(e) {
$('.select2-selection__placeholder').css("font-size", '11px'); // change the font size of the select box
var region = e.target.value;
$.ajax({
url: "{{ url('/dropdown/station?region')}}=" + region, // value.id refers to ring_id
type: "get",
cache: false,
beforeSend: function() {
$('.ajax-loader').css("visibility", "visible");
},
complete: function() {
$('.ajax-loader').css("visibility", "hidden");
},
dataType: 'json',
success: function(data) {
// empty the option before we populate the dropdown
$('#station').empty();
// define default value
$('#station').append('<option value="default" selected="selected" disabled hidden></option>');
$.each(data, function(index, subCatObj) {
// alert(subCatObj.substation_name);
$('#station').append($('<option>').text(index).attr('value', index));
$('#station').append('' + index + '');
});
},
error: function(error) {
console.log(error);
}
});
});
$('.station').on('change', function(e) {
var station = e.target.value;
$.ajax({
url: "{{ url('/dropdown/kv-station?station')}}=" + station, // value.id refers to ring_id
type: "get",
cache: false,
beforeSend: function() {
$('.ajax-loader').css("visibility", "visible");
},
complete: function() {
$('.ajax-loader').css("visibility", "hidden");
},
dataType: 'json',
success: function(data) {
// empty the option before we populate the dropdown
$('#kvStation').empty();
// define default value
$('#kvStation').append('<option value="default" selected="selected" disabled hidden></option>');
$.each(data, function(index, subCatObj) {
// alert(subCatObj.substation_name);
$('#kvStation').append($('<option>').text(index).attr('value', index));
$('#kvStation').append('' + index + '');
});
},
error: function(error) {
console.log(error);
}
});
});
// kv station dropdown event
$('.kvStation').on('change', function(e) {
var station = e.target.value;
$.ajax({
url: "{{ url('/dropdown/ring?station') }}=" + station, // value.id refers to ring_id
type: "get",
cache: false,
beforeSend: function() {
$('.ajax-loader').css("visibility", "visible");
},
complete: function() {
$('.ajax-loader').css("visibility", "hidden");
},
dataType: 'json',
success: function(data, jqXHR) {
// remove the previous data ferom select
$('#ring').empty();
// checking the status code; if 204: no content, then
if (jqXHR.status === 204) {
$('#ring').append('<option value="default" selected="selected">No data</option>');
} else {
$('#ring').append('<option value="default" selected="selected" disabled hidden></option>');
}
// empty the option before we populate the dropdown
$.each(data, function(index, subCatObj) {
$('#ring').append($('<option>').text(subCatObj).attr('value', index));
$('#ring').append('' + index + '');
});
},
error: function(error) {
console.log(error);
}
});
// ring dropdown event
$('.ring').on('change', function(e) {
var id = e.target.value;
window.open('{{url(' / ring ')}}/' + id, '_blank');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="bottom">
<ul>
<li>
<label>Region
<select id="region-select" class=" form-control select2 region" name="region">
<option></option>
#foreach($regions as $region)
<option value="{{$region->region}}">
{{$region->region}}
</option>
#endforeach
</select>
{{--        {!! Form::select('region', $regions,'Please select ...', ['class' => 'region form-control select2', 'id' => 'region-select']) !!}--}}
</label>
</li>
<li>
<label>Station
<select id="station" class=" selectpicker station form-control input-sm" name="station">
<option value=""></option>
</select>
</label>
</li>
<li>
<label>KV Station
<select id="kvStation" class="kvStation form-control input-sm" name="kv-station">
<option value=""></option>
</select>
</label>
</li>
<li>
<label>Ring
<select id="ring" class="ring form-control input-sm" name="ring">
<option value=""></option>
</select>
</label>
</li>
</ul>
<i id="loading-image" hidden class="livicon" data-name="spinner-three" data-size="50" data-c="#fff" data-hc="#fff" data-loop="true"></i>
<div class="ajax-loader">
<img id="loading-image" class="loading-image img-responsive" src="{{ asset('images/ajax-loader.gif') }}">
</div>
</div>

Related

Use Ajax post select modal in PartialView of ASP.NET Core MVC is null

Ajax code
$(function(){
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = new FormData(form.get(0));
$.ajax({
url: actionUrl,
method: 'post',
data: sendData,
processData: false,
contentType: false,
cache: false,
success: function (redata) {
...
},
error: function (message) {
alert(message);
}
})
})
}
In the partial view, I use select object #EmpSelect to add value and text to select object #RolesList, then use ajax post ID, Title, isVirtualGroup and RolesList to controller.
But the RolesList is always null, how can I do fix it?
javascript code
$('#AddRolesGroup').click(function () { $('#EmpSelect :selected').map(function (row, item) { console.log(item.text); $('#RolesList').append("<option value='" + item.value + "'>" + item.text + "</option>") }); });
View about select object part
<div id="area">
<select id="EmpSelect" class="form-select col-md-12" size="8"
multiple aria-label="EmpSelect">
</select>
<button class="btn" type="button" id="ClearSelect">Clear Select Roles</button>
<select asp-for="RolesList" asp-items="Model.RolesList" class="form-select col-md-12" size="8"
multiple aria-label="RolesList">
</select>
</div>
You need to make sure the select is in the form and make sure you have selected values.Here is a demo:
<form id="form1">
<div id="area">
<select id="EmpSelect" class="form-select col-md-12" size="8"
multiple aria-label="EmpSelect">
</select>
<button class="btn" type="button" id="ClearSelect">Clear Select Roles</button>
<select id="RolesList" name="RolesList" class="form-select col-md-12" size="8"
multiple aria-label="RolesList">
<option value="1">role1</option>
<option value="2">role2</option>
<option value="3">role3</option>
</select>
</div>
</form>
<button onclick="postdata()">postdata</button>
js:
function postdata() {
var sendData = new FormData($("#form1").get(0));
$.ajax({
url: "PostData",
method: 'post',
data: sendData,
processData: false,
contentType: false,
cache: false,
success: function (redata) {
//
},
error: function (message) {
alert(message);
}
})
}
action:
public IActionResult PostData(string[] RolesList)
{
return Ok();
}
result:

How to send other variable datas along with new FormData() inside AJAX?

Here I am sending the upload files into FormData() to be accessed in expressjs. And it is working perfectly.
$(".commonForm").submit(function (e) { //For Submitting the Uploaded Files
e.preventDefault();
if(validateForm($(this).attr('name'), text))
{
$.LoadingOverlay("show");
var formData = new FormData(this);
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function(response){
if (response.status == '200') {
$.LoadingOverlay("hide");
swal({
title: "Excellent!",
text: "Files submitted successfully!",
icon: "success",
button: "Ok",
showCancelButton: true
}).then((result) => {
if (result) {
window.location.reload();
}
});
}
},
error: function (e) {
console.log("some error", e);
}
});
}
});
But along with that I want to send one another field data along with formData.
var text = 'Done';
How to send this along with formData in data ?
I am trying this:
data : {
formData:formData,
text:text
}
But then I don't think that I will be able to retrieve the uploaded files data directly with req.files
UPDATE:
route code/expressjs
router.post('/api/upload/:cid',function(req,res,next){
console.log("req.body.text = " + req.body.text + req.query.text);
upload2(req,res,function(err) {
if(err) {
console.log("Error is important = "+ err);
}
else
{
console.log("Uploaded successfully.");
}
})
})
MULTER CODE:
var upload2 = multer({storage: storage2, limits: { fileSize: 1024 * 1024 * 1 }}).array('FileUploadForClient',4);
HTML HANDLEBAR FORM CODE:
<form name="{{this.status}}" class="commonForm" enctype="application/x-www-form-urlencoded" action="/api/upload/{{this.commonID}}" method="post">
<td class="col-sm-2">
<div class="center">
<select name="sourcesSelect" id="{{this.commonID}}" data-notUse="{{this._id}}" data-Id4AddtasksBigpaths="{{this.Id4AddtasksBigpaths}}" class="custom-select sources" placeholder="{{this.status}}" style="font-size:20px; background: {{this.background}}; color: white;" {{this.statusDisabled}}>
<option value="0" >In Progress</option>
<option value="1" >Done</option>
<option value="2" >Rejected</option>
</select>
</div>
</td>
<!-- <td class="col-sm-2"><span id="deadline" style="font-size:14px"><input type="text" class="form-control" value="{{this.deadline}}" readonly/></span></td> -->
<td class="col-sm-1">
<!-- <input type="file" class="btn btn-light" name="FileUploadForClient" multiple required/> -->
<input type="file" id="{{this._id}}" class="form-control" name="FileUploadForClient" multiple required {{this.statusDisabled}} />
</td>
<td>
<button type="submit" class="btn btn-primary btn-block col-sm-2" style="font-size:16px" {{this.statusDisabled}}>Submit</button>
</td>
</form>
Use the method append to add another parameter to the request
var formData = new FormData(this);
formData.append('text', 'text to send in the request ');

Laravel 5 multi dynamic dropdown

I'm trying to use the data of the first dropdown, to fill the second.
An example here:
https://gitlab.com/Bons/laravel5.3_dynamic_dropdown/blob/master/readme.md
Controller functon return data, but second dropdown is empty.
First dropdown:
<span>Country: </span>
<select style="width: 200px" class="country" id="id_country">
<option value="0" disabled="true" selected="true">-Select-</option>
#foreach($countries as $contry)
<option value="{{$contry->id_country}}">{{$contry->name}}</option>
#endforeach
</select>
linked dropdown:
<label>City
<select id="region" class="form-control input-sm" name="region_id">
<option value=""></option>
</select>
</label>
Script:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','.country',function(){
console.log("hmm its change");
var id=$(this).val();
console.log(id)
$.ajax({
type:'get',
url:'{!!URL::to('findRegions')!!}',
data:{'id':id},
success:function(data) {
console.log("success");
console.log(data.length);
console.log(data);
$.each(data, function(index,subCatObj){
// console.log(subCatObj.name)
$('#region').append(''+subCatObj.name+'');
});
},
error:function(){
console.log("error");
}
});
});
});
</script>
Route:
Route::get('/findRegions/','GirlsController#findRegions');
Controller function:
public function findRegions(Request $request){
$id=$request->id;
$regions=Region::select('name')
->where('id_country',$id)
->get();
dump($regions);
return $regions;
}
Here is how i did it,
in routes/web.php
Route::post('select-ajax', 'Main#selectAjax')->name('select-ajax');
in Controller : Main.php
public function __construct()
{
View::share('selectAllCountries', Country::pluck("name","id")->all());
}
public function selectAjax(Request $request)
{
if($request->ajax())
{
$getRegion = Region::where('id_country',$request->id)->pluck("nameOfTheRegion","id")->all();
$data = view('ajax-select',compact('getRegion'))->render();
return response()->json(['options'=>$data]);
}
}
then create a simple blade file name ajax-select.blade.php
<option selected disabled>--- Select Region---</option>
#if(!empty($getRegion))
#foreach($getRegion as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
#endif
Ajax call
{!! Form::select('country',[' '=>'--- Select Country ---']+$selectAllCountries,null,['class'=>'form-control']) !!}
{!! Form::select('region',[' '=>'--- Select Region---'],null,['class'=>'form-control']) !!}
<script>
$("select[name='country']").change(function(){
var id = $(this).val();
var token = $("input[name='_token']").val();
$.ajax({
url: "{{ route('select-ajax') }}",
method: 'POST',
data: {'id':id, '_token':token},
success: function(data) {
$("select[name='region']").html('');
$("select[name='region']").html(data.options);
},
error:function(){
alert("error!!!!");
}
});
});
</script>
Hope this helps

How To open page in new window with ajax

I Have this lisemenu in a Form
<select name="Exam" id="Exam">
<option value="Hematology">Hematology</option>
<option value="G. Urin Exam">G. Urin Exam</option>
<option value="G. Stool Exam">G. Stool Exam</option>
</select>
<input name="PtID" type="hidden" id="PtID" value="<?php echo $_POST['PtID']; ?>" />
</p></th>
<th scope="col"><input type="button" name="button" id="button" value="Button" onclick="open_exam()" />
and I Have This Script
<script type="text/javascript">
function open_exam(){
var myurl;
switch($("#Exam").val())
{
case "Hematology":
myurl = "testspg/Hematology.php";
break;
case "G. Urin Exam":
myurl = "testspg/Gurin.php";
break;
case "G. Stool Exam":
myurl = "testspg/Gstool.php";
break;
// etc
}
$.ajax({
url: myurl,
type: 'POST',
data: { PtID: $('#PtID').val() },
success: function(data){
$(".myresult").html(data);
}
})
}
</script>
I want to open myurl in new window instead of .myresult Class
How can I do that with this script

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