select box using AJAX - 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?

Related

Getting value from (select2) to another filed input laravel

I have select2 field input. After using select2 its will showing new column and data from this input selected.
I have referenced like this link. So after I using select2, this value will show in a new column. But I don't know how to catch this data. I am using Laravel and this is my controller and view:
Controller
$collection = Alat::get(['nama_alat','no_inventaris','status_alat','id']);
foreach ($collection as $item) {
$inven[$item->id] = $item->no_inventaris.'-'.$item->nama_alat;
}
This is will shown in columns no_inventaris and nama_alat in the select2. But in the $collection, I have status_alat, this data is what I need to display in another column.
This is my view:
// This is form Select2
<div class="form-group">
<label>Pilih Inventaris</label>
<select class="form-control select2bs4" name="alat_id" id="alat_id" style="width: 100%;" aria-hidden="true" onchange="Show()">
<option value=""></option>
#foreach($inven as $id => $item )
<option value="{{ $id }}">{{ $item }} </option>
#endforeach
</select>
</div>
// This is form what i need to show another value
<div class="form-group" id="divid" style="display:none">
<label class="control-label" for="title">Kondisi Alat Sekarang:</label>
<input type="text" name="" class="form-control" id="value" data-error="Please enter title." readonly />
<div class="help-block with-errors"></div>
</div>
Here's my Javascript:
<script>
function Show()
{
var fieldValue = $('#alat_id').val();
if(fieldValue == "")
{
document.getElementById("divid").style.display = 'none';
}
else{
document.getElementById("divid").style.display = 'inline'
}
}
</script>
This data I need to catch in the controller $collection as status_alat. How can I catch this data after input the select2 and showing in the new column? This column is shown, but I don't know how to catch this data. Sorry for my bad English
The best solution should be using ajax, it is quite complicated to access a PHP collection variable inside a javascript. If it were me, I would create a function that fetch the selected select2 data by its id. This is my example code :
<script>
function select2Changed()
{
var alat_id = $('#alat_id').val();
if(fieldValue == ""){
document.getElementById("divid").style.display = 'none';
} else{
document.getElementById("divid").style.display = 'inline';
$.ajax({url: "[url]/get-alat-status/"+alat_id, success: function(result){
document.getElementById("value").value = result;
}});
}
}
</script>

Laravel Ajax dropdown example

can someone please share working example of laravel ajax dropdown. there are so many examples about dependable dropdown, but i want simple dropdown of only one column, i have two tables teacher and nation, when teacher profile is open i want dropdown of nationality using ajax.
i have done it without ajax, but i don't know how to do with ajax.
without ajax:
<select name="nation_id" class="custom-select" >
<option selected value=" ">Choose...</option>
#foreach($nations as $nations)
<option value="{{#$nation_id}}" {{#$teacher->nation_id== $nations->id ? 'selected' : ''}} >{{#$nations->nation}}</option>
#endforeach
Controller:
$nations = nation::all();
<select class="form-control" name="nation_id" id="nation_id">
<option value="">Select nation</option>
#foreach($nations as $nation)
<option value="{{ $nation->nation_id }}">{{ $nation->nation_name }} </option>
#endforeach
</select>
<select class="form-control" name="teacher" id="teacher">
</select>
now the ajax code:
<script type="text/javascript">
$('#nation_id).change(function(){
var nid = $(this).val();
if(nid){
$.ajax({
type:"get",
url:"{{url('/getTeacher)}}/"+nid,
success:function(res)
{
if(res)
{
$("#teacher").empty();
$("#state").append('<option>Select Teacher</option>');
$.each(res,function(key,value){
$("#teacher").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
</script>
now in controller file;
public function getTeacher($id)
{
$states = DB::table("teachers")
->where("nation_id",$id)
->pluck("teacher_name","teacher_id");
return response()->json($teachers);
}
And last for route file:
Route::get('/getTeacher/{id}','TeachersController#getTeacher');
Hope this will work..
Good Luck...
Create a route for your method which will fetch all the nations-
Route::get('nations-list', 'YourController#method');
Create a method in your controller for the above route-
public function method()
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations)
}
Add a select box like this in your HTML-
<select id="nation_id" name="nation_id"></select>
If you want to auto select the option based on a variable then you can do this-
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id" value="{{ $teacher->nation_id ?? '' }}">
And then add this script in your HTML to fetch the nation list on page load-
<script>
$(document).ready(function($){
$.get('nations-list', function(data) {
let teacher_nation_id = $('#teacher_nation_id').val();
let nations = $('#nation_id');
nations.empty();
$.each(data, function(key, value) {
nations.append("<option value='"+ key +"'>" + value + "</option>");
});
nations.val(teacher_nation_id); // This will select the default value
});
});
</script>

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

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>');
}
}
});
});

AJAX form executed by onblur OR change event

I have a form where the user will enter a number into a text field. Then, select another number from a dropdown menu. I want the AJAX to execute each time they go from field to field. This is so that it does a calculation in real-time.
I would imagine the text field would be using "onblur" and the dropdown using "change" or "onchange"... but how do I write the script to do EITHER depending on which field they are currently on? Can you set it to do both?
EDIT: New attempt with new variable labels.
<script type="text/javascript">
function postData(){
var widthX = $('#width_str').val();
var heightX = $('#height_str').val();
var prodidX = $('#prodid').val();
var roomX = $('#room_str').val();
$.post('db_query.php',{widthX:widthX, heightX:heightX, prodidX:prodidX, roomX:roomX},
function(data){
$("#search_results").html(data);
});
}
$(function() {
$("#lets_search").bind('submit',function() {postData()});
$("#room_str").bind('change', function() {postData()});
$("#width_str").bind('change', function() {postData()});
$("#height_str").bind('change',function() {postData()});
});
</script>
Part of the form here....
<form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
<input type="hidden" value="1" value="<?php echo stripslashes($_GET['prodid']); ?>" name="prodid" id="prodid">
room name:
<select name="room_str" id="room_str">
<option value="Dining">Dining</option>
<option value="Bathroom">Bathroom</option>
<option value="Kitchen">Kitchen</option>
</select>
height:
<select name="height_str" id="height_str">
<option value="30">30"</option>
<option value="31">31"</option>
<option value="32">32"</option>
<option value="33">33"</option>
<option value="34">34"</option>
<option value="35">35"</option>
<option value="36">36"</option>
<option value="37">37"</option>
</select>
<br>
width:
<select name="width_str" id="width_str">
<option value="30">30"</option>
<option value="31">31"</option>
<option value="32">32"</option>
<option value="33">33"</option>
<option value="34">34"</option>
<option value="35">35"</option>
<option value="36">36"</option>
<option value="37">37"</option>
</select>
<input type="submit" value="send" name="send" id="send">
</form>
The php page that processes the data...
<?php
include('db_pbconnection.php');
$tax = .06;
$tax2 = 1.06;
$grandtotal = 50;
$query = mysql_query(" SELECT * FROM price_dimensions WHERE prodid = '".$_POST['prodidX']."' AND height >= '".$_POST['heightX']."' AND width >= '".$_POST['widthX']."' ORDER BY height ASC, width ASC LIMIT 1 ");
echo '<div>';
while ($data = mysql_fetch_array($query)) {
echo '
<div style="background-color:pink;">
<div style="clear:both; font-size:18px;">height: '.$data["height"].'</div><br>
<div style="clear:both; font-size:18px;">width: '.$data["width"].'</div>
<div style="clear:both; font-size:18px;">unit price: '.$data["price"].'</div>
<div style="clear:both; font-size:18px;">tax: '.(($data["price"])*($tax)).'</div>
<div style="clear:both; font-size:18px;">grand total:'.(($data["price"])*($tax2)).'</div>
</div>';
}
echo '</div>';
?>
If I understand you correctly, you can call the AJAX from any area by moving the code into a separate function and binding any event to that function.
function postData(){
var value = $('#str').val();
var valueH = $('#strH').val();
var prodid = $('#prodid').val();
$.post('db_query.php',{valueH:valueH, value:value, prodid:prodid},
function(data){
$("#search_results").html(data);
});
return false;
}
$(function() {
$("#lets_search").bind('submit',function() {postData()});
$("#strH").bind('change', function() {postData()});
$("#str").bind('blur',function() {postData()});
});

Resources