Laravel Datatables custom select search - laravel

I have a dropdown with option to select if you want to see domens that are expiring in given date.
But once i pick date i will get pure json code with right result.
This is my form above table
<form method="post" action="{{ action('DomenController#tabela') }}" id="klijent_rok" onchange="document.getElementById('klijent_rok').submit()">
#csrf
<div class="form-group row">
<label for="istice_za" class="ml-md-auto col-form-label text-md-left" style="padding-right: 10px;">Ističu u roku od:</label>
<select name="istice_za" id="istice_za" class="form-control" style="width: 140px" size="1">
<option value="99" #if($istice_za == '99') selected='selected' #endif>-neodređeno-</option>
<option value="7" #if($istice_za == '7') selected='selected' #endif>za 7 dana</option>
<option value="30" #if($istice_za == '30') selected='selected' #endif>za 30 dana</option>
<option value="60" #if($istice_za == '60') selected='selected' #endif>za 60 dana</option>
<option value="istekli" #if($istice_za == 'istekli') selected='selected' #endif>istekli</option>
</select>
Poništite filtere
</div>
</form>
And this is mine controller for server side Datatable
if(!empty($request->istice_za) && $request->istice_za != 99) {
$date = Carbon::now();
$new_date = Carbon::now();
if($request->istice_za != 'istekli') {
if($request->istice_za == 7) {
$istice_za = 7;
$new_date->addDays(7);
}
if($request->istice_za == 30) {
$istice_za = 30;
$new_date->addDays(30);
}
if($request->istice_za == 60) {
$istice_za = 60;
$new_date->addDays(60);
}
$domen = Domen::where('datum_end', '<', $new_date)
->Where('datum_end', '>', $date)
->with('klijent');
}
else {
$domen = Domen::where('datum_end', '<', $date)->with('klijent');
$istice_za = 'istekli';
}
}
else {
$domen = Domen::with('klijent');
$istice_za = 99;
}
return datatables()->of($domen)->make(true);
And these are my routes
Route::get('/lista-domena/tabela', 'DomenController#tabela');
Route::post('/lista-domena/tabela', 'DomenController#tabela');
What am I doing wrong and not getting that data in my table?

For first, your code is not running the query, you need to add ->get() or first() to get the data.
$domen = Domen::where('datum_end', '<', $date)->with('klijent')->get();
Or,
$domen = Domen::with('klijent')->get();

I managed to solve it. The problem was that i didn't send data from select to my controller. I edited my form to be like this:
<form method="post" action="{{ action('DomenController#tabela') }}" id="klijent_rok">
And then added this in script:
$('#klijent_rok').on('change', function(e) {
table.draw();
});
and changed Ajax to this:
ajax: {
url: '/lista-domena/tabela',
data: function ( d ) {
d.istice_za = $('#istice_za').val();
},
}...

Html:
<table id="affected-requirement-table" class="table table-hover table-sm table-bordered">
<!--Table head-->
<thead>
<tr>
<th>Requirements</th>
<th>Effect Type</th>
</tr>
</thead>
<!--Table head-->
<!--Table body-->
<tbody>
<!-- Ajax Load -->
</tbody>
<!--Table body-->
</table>
Jquery
$(document).ready(function () {
var affectedRequirementsTable = $('#affected-requirement-table').DataTable({
"scrollY": "200px",
"scrollCollapse": true,
"paging": false,
processing: true,
serverSide: true,
bFilter: false,
"bInfo": false,
"bPaginate": true,
"ordering": false,
"bLengthChange": false,
ajax: {
url: '{!! \Illuminate\Support\Facades\URL::to("cr/requirements-datatables") !!}'
},
columns: [
{data: 'number'},
{data: 'effect-type'}
],
// "fnCreatedRow" : function (row, data, dataIndex) {
// var div = document.createElement("div");
// $(div).html('<select name= "changeRequest[]" class="form-control effect-type-select" id="mySelect"> <option selected="selected" value="None">None</option> <option value="Addition">Addition</option> <option value="Deletion">Deletion</option> </select>');
// $(row).children("td:last-child").append(div);
// }
});
// draw the table
affectedRequirementsTable.draw();
$("#affected-requirement-table").on('change',".effect-type-select",function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
console.log(valueSelected);
});
})
routes:
Route::get('cr/requirements-datatables', "ChangeRequestController#requirementsAndEffectTypesDatatables");
Controller:
public function requirementsAndEffectTypesDatatables(ChangeRequests $request)
{
$changeRequest = DB::table('requirement')->select(['number','id']);
return DataTables::of($changeRequest)->addColumn('effect-type', function ($changeRequest) {
return '
<select name= "changeRequest[]" class="form-control effect-type-select" id="mySelect">
<option selected="selected" value="None">None</option>
<option value="Addition">Addition</option>
<option value="Deletion">Deletion</option>
</select>';
})->rawColumns(['effect-type'])->make(true);
}

Related

Load dependent dropdown on Edit Laravel

How to automatically load or retrieve the subcategory/dependent dropdown based on the selected value of parent dropdown in Edit. If I click the edit, the doctor should instantly load. I've been searching for hours for the solutions please help.
Blade
<select name="clinic_id" data-placeholder="Search" data-allow-clear="true"
class="form-control select2bs4" style="width: 100%;" id="load_clinic">
<option selected="selected"></option>
#foreach ($clinic as $id => $item)
<option value="{{ $id }}"
{{ $schedule->clinic_id == $id ? 'selected' : '' }}>
{{ $item }}
</option>
#endforeach
</select>
<select name="doctor_id" data-placeholder="Search" data-allow-clear="true"
class="form-control select2bs4" style="width: 100%;" id="load_doctor">
</select>
Javascript
$(document).ready(function() {
$('#load_clinic').on('change', function(e) {
var clinic_id = e.target.value;
if (clinic_id) {
$.ajax({
url: "{{ route('getDoctor') }}",
type: "POST",
data: {
clinic_id: clinic_id,
_token: "{{ csrf_token() }}"
},
success: function(data) {
if (data) {
$('#load_doctor').empty();
$('#load_doctor').append(
'<option value=""> Select Doctor</option>');
$.each(data, function(key, value) {
$('#load_doctor').append($(
"<option/>", {
value: key,
text: value
}));
});
} else {
$('#load_doctor').empty();
}
}
})
} else {
$('#load_doctor').empty();
}
});
});
Controller
public function edit($id)
{
$schedule = Schedule::findOrFail($id);
$clinic = Clinic::pluck('name', 'id');
$doctor = Doctor::get()->pluck('full_name', 'id');
return view('admin.schedule.edit', compact('schedule', 'doctor', 'clinic'));
}
public function getDoctor(Request $request)
{
$id = $request->clinic_id;
$doctor = Doctor::where('clinic_id', $id)->get()->pluck('full_name', 'id');
return response()->json($doctor);
}
You can get initial select options with PHP before resorting to ajax.
Consider using plural nouns when you are using get() and singular when using i.e. first()
Also, consider using #if(condition) #endif instead of ternary operators in blade
This is solution with PHP, if you want to get doctors with AJAX, in addition to onChange listener, you should also call it when page loads,
Controller
public function edit($id)
{
$schedule = Schedule::findOrFail($id);
$clinic = Clinic::pluck('name', 'id');
$doctor = Doctor::where('clinic_id', $schedule->clinic_id)->get();
return view("admin.schedule.edit", compact('schedule', 'doctor', 'clinic'));
}
Blade
<select name="clinic_id" data-placeholder="Search" data-allow-clear="true"
class="form-control select2bs4" style="width: 100%;" id="load_clinic">
<option selected="selected"></option>
#foreach ($clinic as $id => $item)
<option value="{{ $id }}"
{{ $schedule->clinic_id == $id ? 'selected' : '' }}>
{{ $item }}
</option>
#endforeach
</select>
<select name="doctor_id" data-placeholder="Search" data-allow-clear="true"
class="form-control select2bs4" style="width: 100%;" id="load_doctor">
#foreach($doctor as $item)
<option value="{{$item->id}}">{{$item->full_name}}</option>
#endforeach
</select>

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

select box using AJAX

I have a select form which has three fields, Location, Estate and Size that populate dynamically using ajax.
When a user selects a town, the estates drop down options appear with respect to the town selected.
When the user clicks on search button, results based on the selection should appear.
According to my code, when I dd the variables $Estate and $Size in my post method, I get the values selected by the user on the form. This is what I want.
However, when I dd $Location, I get the id number instead of the value the user selected on the form.
This is my form :
<form class="form-inline" id="search-bar" action="{{route('post_index')}}" method="post">
{{ csrf_field() }}
<select class="form-control productcategory" name="Location" id="product_cat_id">
<option value="0" disabled="true" selected="true">Town</option>
#foreach($cities as $city)
<option value="{{$city->id}}">{{$city->product_cat_name}}</option>
#endforeach
</select>
<select class="form-control productname" name="Estate">
<option value="0" disabled="true" selected="true">Estate</option>
</select>
<select class="form-control" name="Size">
<option value="0" disabled="true" selected="true">Size</option>
<option value="Bedsitter">Bedsitter</option>
<option value="One Bedroom">One Bedroom</option>
<option value="Two Bedroom">Two Bedroom</option>
<option value="Three Bedroom">Three Bedroom</option>
</select>
<button type="submit" class="btn btn-default">Search</button>
</form>
This is my AJAX code :
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change', '.productcategory', function(){
//console.log("Shit is working");
var new_id=$(this).val();
//console.log(cat_id);
var div=$(this).parent();
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findEstateName')!!}',
data:{'id':new_id},
success:function(data){
//console.log('success');
console.log(data);
//console.log(data.length);
op+='<option value="0" selected disabled>chose estate</option>';
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].Estate+'">'+data[i].Estate+'</option>';
}
div.find('.productname').html(" ");
div.find('.productname').append(op);
},
error:function(){
}
});
});
$(document).on('change','.productname',function (){
var prod_id=$(this).val();
var a=$(this).parent();
console.log(prod_id);
var op="";
});
});
</script>
This is my post method :
public function postIndex(){
//echo "success";
$Location = Input::get('Location');
$Estate = Input::get('Estate');
$Size = Input::get('Size');
$validator= Validator::make(
array(
'Location'=>$Location,
'Estate'=>$Estate,
'Size'=>$Size
),
array(
'Location'=>'required',
'Estate'=>'required',
'Size'=>'required'
)
);
if ($validator->fails()) {
return redirect()->route('home-index')->withErrors($validator);
// echo "fail";
}else{
$houses=DB::table('houses')->where('Location', $Location)->where('Size', $Size)->where('Estate', $Estate)->get();
dd($Location);
//$towns = DB::table('houses')->pluck('Location', 'Location');
//$estates = DB::table('houses')->pluck('Estate', 'Estate');
$cities=ProductCat::all();
$data = [
'house' => $houses,
//'towns' => $towns,
//'estates' => $estates,
'cities' => $cities
];
//dd($data);
if (count($houses)) {
return View('pages.home', $data);
}else{
Session::flash('fail', 'Sorry, no results found...');
return View('pages.home',$data, ['FailMessage' => 'Sorry no results found..'])->withHouse($houses);
}
}
}
What do I need to do so that when I dd $Location, I get the Location name selected by the user?

Vue.js sorting is not working when fetching from Laravel

Currently this is for listing customer data from database. Data is fetching using Laravel 5. At present data is fetching and listing properly. This page contains pagination, filter search and sorting functionality. My problem is sorting is not working properly. Could you please help me to sort out this issue? I am using Vue.js version 1.0.25
Here is the short code, only the sorting part
View
<th v-for="key in columns" #click="sortBy(key)" :class="{active: sortKey == key}">
#{{ colTitles[key] }}
</th>
<tr v-for="(index, item) in items | filterBy searchQuery | orderBy sortKey reverse">
........
JS
data: {
sortKey: '',
reverse: false,
.........
sortBy: function(sortKey) {
this.reverse = (this.sortKey == sortKey) ? ! this.reverse : false;
this.sortKey = sortKey;
}
Full code
dashboard.blade.php
<div class="container">
<div class="row">
<h1 class="page-header">{{ trans('messages.customerListPageHeadingLabel') }}</h1>
<div id="app">
<div class="form-group col-md-4">
<form id="search" class="form-inline">
<label for="query">{{ trans('messages.customerListPageSearchBox') }} </label>
<input name="query" class="form-control" v-model="searchQuery">
</form>
</div>
<br>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th v-for="column in columns" #click="sortBy(column)">
#{{ colTitles[column] }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(index, item) in items | filterBy searchQuery | orderBy sortKey reverse">
<td>#{{ item.erp_id }}</td>
<td>#{{item.firstname}}</td>
<td>#{{item.lastname}}</td>
<td>#{{item.email}}</td>
<td>#{{item.phone_1}}</td>
<td>#{{item.status}}</td>
<td>#{{item.created_on}}</td>
</tr>
</tbody>
</table>
<nav>
<ul class="pagination">
<li v-if="pagination.current_page > 1">
<a href="#" aria-label="Previous"
#click.prevent="changePage(pagination.current_page - 1)">
<span aria-hidden="true">«</span>
</a>
</li>
<li v-for="page in pagesNumber"
v-bind:class="[ page == isActived ? 'active' : '']">
<a href="#"
#click.prevent="changePage(page)">#{{ page }}</a>
</li>
<li v-if="pagination.current_page < pagination.last_page">
<a href="#" aria-label="Next"
#click.prevent="changePage(pagination.current_page + 1)">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
Laravel Controller
public function listCustomers()
{
$results = Customer::select('id', 'erp_id', 'firstname', 'lastname', 'email', 'phone_1', 'status', DB::raw("DATE_FORMAT(created_at, '%d.%m.%Y %H:%i') AS created_on"))
->orderBy('id', 'desc')->latest()->paginate(25);
$response = [
'pagination' => [
'total' => $results->total(),
'per_page' => $results->perPage(),
'current_page' => $results->currentPage(),
'last_page' => $results->lastPage(),
'from' => $results->firstItem(),
'to' => $results->lastItem()
],
'data' => $results
];
return $response;
}
Vue JS
new Vue({
el: '#app',
data: {
sortKey: '',
reverse: false,
columns: ['erp_id', 'firstname', 'lastname', 'email', 'phone_1', 'status', 'created_on'],
colTitles: {'erp_id':'#lang('messages.customerListPageTableCustomerNo')', 'firstname':'#lang('messages.customerListPageTableFirstname')', 'lastname':'#lang('messages.customerListPageTableLastname')', 'email':'E-Mail', 'phone_1':'#lang('messages.customerListPageTablePhone')', 'status':'Status', 'created_on':'#lang('messages.customerListPageTableAddedDate')'},
pagination: {
total: 0,
per_page: 7,
from: 1,
to: 0,
current_page: 1
},
offset: 4,// left and right padding from the pagination <span>,just change it to see effects
items: []
},
ready: function () {
this.fetchItems(this.pagination.current_page);
},
computed: {
isActived: function () {
return this.pagination.current_page;
},
pagesNumber: function () {
if (!this.pagination.to) {
return [];
}
var from = this.pagination.current_page - this.offset;
if (from < 1) {
from = 1;
}
var to = from + (this.offset * 2);
if (to >= this.pagination.last_page) {
to = this.pagination.last_page;
}
var pagesArray = [];
while (from <= to) {
pagesArray.push(from);
from++;
}
return pagesArray;
}
},
methods: {
fetchItems: function (page) {
var data = {page: page};
this.$http.get('/list/customers', data).then(function (response) {
//look into the routes file and format your response
this.$set('items', response.data.data.data);
this.$set('pagination', response.data.pagination);
}, function (error) {
// handle error
});
},
changePage: function (page) {
this.pagination.current_page = page;
this.fetchItems(page);
},
sortBy: function(sortKey) {
this.reverse = (this.sortKey == sortKey) ? ! this.reverse : false;
this.sortKey = sortKey;
}
}
});
the last parameter of orderBy should be 1 or -1, while you provide either true or false with the value of reverse
https://jsfiddle.net/Linusborg/spwwxLvy/
change this:
this.reverse = (this.sortKey == sortKey) ? ! this.reverse : false;
to this:
this.reverse = (this.sortKey == sortKey) ? 1 : -1;
also change the initial value in data() accordingly.

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