Laravel 5.4 - Populate dropdown based on another dropdown selected value - laravel

I want when select one value from first dropdown to automatcly populate another dropdown based on first dropdown value.
My view:
<label for="category">Catégorie(s):</label>
{!! Form::select('category', $category,null, array('class' => 'form-
control')) !!}
<label for="brand">Marque:</label>
{!! Form::select('brand_name', $brand_name,null, array('class' => 'form-control')) !!}
My controller:
public function index()
{
$category = Category::pluck('categoryName', 'id');
$brand = Brand::pluck('brandName', 'id');
return view ( 'site.indexS',compact('brand','category') );
}
How to populate another dropdown? Any idea?

you can easily do it with a little bit of ajax and get method. May be you are trying to load brand depend on category lets roll :
Your controller:
public function index()
{
$category = Category::pluck('categoryName', 'id');
// no need to query brand here because we will load it depend on category
$brand = [];
return view ( 'site.indexS',compact('brand','category') );
}
// here we are adding another method in your controller which will return brand object depend on category id
public get_brand($categpry_id){
// hope your brand table contain category_id or any name as you wish which act as foreign key
$brands= Brand::where('category_id',$category_id)
->pluck('brandName','id');
return json_encode($brands);
}
Now in route we need to add this to hit this url :
Route::get('get-brand','YourControllerName#get_brand');
In view :
{{-- i am adding id for both dropdown --}}
Catégorie(s):
{!! Form::select('category', $category,null, array('id' => 'category_dropdown','class' => 'form-
control')) !!}
<label for="brand">Marque:</label>
{!! Form::select('brand_name', $brand_name,null, array('id' => 'brand_dropdown','class' => 'form-control')) !!}
now in our view file we need to use ajax, there is many other way i am preferring ajax here
<script type="text/javascript">
var url = "{{url('/')}}";
</script>
<script type="text/javascript">
$('#category_dropdown').on('change', function() {
$('#brand_dropdown').empty();
var id = $('#category_dropdown').val();
$('#brand_dropdown').html('<option selected="selected" value="">Loading...</option>');
var url = url + '/get-brand/'+id;
$.ajax({
url: url,
type: "GET",
dataType: "json",
success:function(data) {
//console.log(data);
$('#brand_dropdown').html('<option selected="selected" value="">Select Brand</option>');
$.each(data, function(key, value) {
$('#brand_dropdown').append('<option value="'+key+'">'+value+'</option>');
});
}
});
});
</script>

Related

Post 403 forbidden on Yii2 Ajax Call

I know there's other topic on this in stackoverflow but it still didn't work for me. I try to make a simple dynamic menu that generate dynamic content based on the chosen <li> id.
This is the code to generate the menu :
foreach($cabang as $index=>$model){
echo '<li id='.$model->idDpd->id_dpd.'>
<a class="nav-link" href="#" role="tab" data-toggle="tab">'.$model->idDpd->dpd.'</a>
</li>';
}
The menu is created successfully. But I have the problem with the content generated with Ajax
This is what I have in my view file :
$script = <<< JS
$(document).ready(function(){
function load_page_details(id)
{
$.ajax({
url: "<?=Url::to(['/site/fetch']) ?>",
method:"POST",
data:{id:id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success:function(data)
{
$('#page_details').html(data);
}
});
}
//load page-details where the id in the database table equals 1. Set the default to 1 while page is loading for the first time.
/* load_page_details(1);*/
$('.nav li').click(function(){
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script)
?>
This is my SiteController and the action :
public function actionFetch(){
if (Yii::$app->request->isAjax) {
// fetch the $_POST["id"]
$data = Yii::$app->request->post('id');
if(isset($data))
{
$query= Cabang::find()->where(['id_dpd'=> $data])
->joinWith('idDpd')
->all();
$output = '';
foreach($query as $model)
{
$output .= '
<div role="tabpanel" class="col-lg-4 tab-pane fade show active" >
<div class="col-md-12">
<h4>'.$model->kota.'</h4>
<p>'.$model->alamat.'</p>
<p>'.$model->telp.'</p>
<p>'.$model->email.'</p>
<p>'.$model->jadwal.'</p>
</div>
</div>
';
}
/* echo $output;*/
// return Json
return \yii\helpers\Json::encode($output);
}
}
}
The error caught in my console in chorome dev tool : jquery.js:9175 POST http://localhost/%3C?=Url::to([%27/site/fetch%27])%20?%3E 403 (Forbidden)
I tried to make the fetch function to a new php file and link the URL in my Ajax to that file (not to a controller or SiteController in my case) like : url: url:"site/fetch.php",but it returned jquery.js:9175 POST http://localhost/site/fetch.php 404 (Not Found)
What am I doing wrong? I have spent two days without solution. Thanks for the help!
Your PHP is not correct - you cannot use <?= /* ... */ ?> inside of heredoc. You need to use temporary variable:
$url = Url::to(['/site/fetch']);
$script = <<<JS
$(document).ready(function () {
function load_page_details(id) {
$.ajax({
url: "$url",
method: "POST",
data: {id: id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success: function (data) {
$('#page_details').html(data);
}
});
}
$('.nav li').click(function () {
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script);

Why the if condition does not filtering the results?

I want to create advance search filtering staff data according to certain criteria chosed by users. This application developed using laravel 5. I am querying the data using ajax function and if statement to filter the criteria. The results appear but it does not filter any condition in the if statement.
The controller of the filtering condition is this:
public function kakitangan(Request $request)
{
$query = DB::table('itemregistrations')
->select('itemregistrations.ItemRegistrationID','itemregistrations.name', 'itemregistrations.Nobadan');
if ($request->section != ""){
$query->where('SectionID', $request->section);
}
$newitem = $query->get();
return response::json($newitem);
}
I also have tried this:
$query = DB::table('itemregistrations')
->select('itemregistrations.ItemRegistrationID','itemregistrations.name', 'itemregistrations.Nobadan');
if(request('section')) {
$query->where('SectionID', request('section'));
}
$newitem = $query->get();
return response::json($newitem);
But the result is the same..all data in itemregistrations appear in the output page. Although I select another section criteria.
This is the view page code for selection:
<div class="row">
<div class="col-lg-2">
{{ Form::label('Seksyen', 'Seksyen') }}
</div>
<div class="col-lg-2">
{{ Form::select('section', $sections, '', ['class' => 'form-control select2', 'placeholder' => '--pilih--']) }}
</div>
</div>
</div>
The selection id is from controller function:
$sections = Section::pluck('sectionname', 'SectionID');
//sent to html view
return view('carian.index', compact('sections'));
Button to call ajax function to get the query:
<button class="btn btn-primary btn-md" id="cari">Cari</button>
The code for results appear:
<script type="text/javascript">
$( "#cari" ).click(function() {
var seksyen = $("#section").val();
$.ajax({
url: '{{ url('kakitangan') }}',
data: {'section': seksyen},
dataType: 'json',
success: function (data) {
console.log(data);
$('#datatable tr').not(':first').not(':last').remove();
var html = '';
for(var i = 0; i < data.length; i++){
html += '<tr>'+
'<td>' + data[i].name + '</td>' +
'</tr>';
}
$('#datatable tr').first().after(html);
},
error: function (data) {
}
});
});
</script>
Should be when the user select a section, only staffs of the section appear. But now all staffs appear when select any section.
I just tried to test whether the section value is correctly passed to the controller using this in controller:
$try=$request->input('section');
return response::json($try);
It results empty array..no value passed? Is it the section value is not passed correctly? How to correct this problem?
You are passing the section as a post param while you performing a GET request.
Using jQuery you can send this as a query string using:
var seksyen = $("#section").val();
$.ajax({
url: '{{ url('kakitangan') }}?' + $.param({'section': seksyen}),
dataType: 'json',
...
In your controller you can also explicitly check if a request contains a query string using the has method on a request
if(request()->has('section')) {
$query->where('SectionID', request('section'));
}
EDIT:
using the laravel collective Form helpers you can specific the field id using the following (note the fourth argument id)
{{ Form::select('section', $sections, '', ['id' => 'section', 'class' => 'form-control select2', 'placeholder' => '--pilih--']) }}

Codeigniter auto suggestion text box

I'm using codeigniter in my project and want to implement a text box which suggests related word s from the data base. In this one I want to get the ID of the selected vehicle. But so far I was only able to retrieve the vehicle names with out IDs.
The code so far,
Model
function searchVehicle($name){
$this->db->like('Name', $name, 'both');
return $this->db->get('vw_vehicle_search')->result();
}
Controller
public function vehicle_search(){
$this->load->model('model_vehicle');
if(isset($_GET['term'])){
$result = $this->model_vehicle->searchVehicle($_GET['term']);
if(count($result)>0){
foreach($result as $object)
$arr_result[] = $object->Name;
echo json_encode($arr_result);
}
}
}
View
<script type="text/javascript">
$(document).ready(function(){
$('#vehicle_name').autocomplete({
source: "<?php echo base_url();?>vehicle/vehicle_search/?"
});
});
</script>
<div class="col-md-4">
<?php
$input_data = array(
'name' => 'vehicle_name',
'id' => 'vehicle_name',
'class' => 'form-control'
);
echo form_input($input_data)?>
</div>
How can I pass the id of the vehicle with this one and get the id when i select a vehicle to insert to the db.
Thank you.
Try it in this way:
controller:
public function vehicle_search(){
$this->load->model('model_vehicle');
if(isset($_GET['term'])){
$result = $this->model_vehicle->searchVehicle($_GET['term']);
if(count($result)>0){
foreach($result as $object)
$arr_result[] = array( 'label' => $object->Name, 'value' => $object->id);
echo json_encode($arr_result);
}
}
}
View:
$(document).ready(function(){
$('#vehicle_name').autocomplete({
source: "<?php echo base_url();?>vehicle/vehicle_search/?",
select: function(event, ui) {
event.preventDefault();
$("#vehicle_name").val(ui.item.label);
//$("#vehicle_name-hidden").val(ui.item.value);
},
focus: function(event, ui) {
event.preventDefault();
$("#vehicle_name").val(ui.item.label);
}
});
});

Getting Ajax to display your search result from a class

I'm working with a recipe API and at the moment you get an error because I'm calling for something that doesn't exist ($contentSearch for example) and I think I can solve this with using Ajax, and no matter what I want to use it to learn how it works.
I'm using fork2fork API and working in Laravel 5.
So far I've looked around but haven't found anything that works. Maybe because I'm calling for a function and from there getting the result?
Feel free to mess up my entire code, I want to learn how to make it right instead of making it just work!
And to make my question clear: How do I show my result from the search by using Ajax?
Here is the html:
#extends('app')
#section('content')
{!! Form::open(['url' => 'searchRecipe']) !!}
{!! Form::text('search') !!}
{!! Form::submit('Search recipe') !!}
{!! Form::close() !!}
<p>if you lucky and have more than one thing in your fridge, separate them with a ',' and nothing else. As in no space.</p>
<div class="text-info">
<ul class="list-unstyled">
#foreach($contentSearch->recipes as $recipe)
<li>{{$recipe->title}}</li>
#endforeach
</ul>
</div>
#stop
And here is the function that is getting called if you push the submit button:
public function getSearch() {
$apiKey = "thats a secret i never tell";
$search = Request::get('search');
// insert search and API key in URL
$apiUrl = "http://food2fork.com/api/search?key=" . $apiKey
. "&q=". $search ;
// get the content of the file
//header('Content-Type: application/json');
$contentSearch = json_decode(file_get_contents($apiUrl));
return view('index', compact('contentSearch'));
}
I'm not sure I've fully understood the question but I hope this helps.
View
{!! Form::open(['url' => 'recipes']) !!}
{!! Form::text('search', null, ['id' => 'search']) !!}
{!! Form::submit('Search recipe') !!}
{!! Form::close() !!}
<ul id="result"></ul>
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script>
$(document).ready(function(){
// get the form submit event
$('form').submit(function(event){
// stop the form from submitting
event.preventDefault();
// the form object
var form = $(this);
// perform ajax post request
$.post(
form.attr('action'), // this will go to form url
form.serialize(), // grab the form data
function(data) { // do something with the response
console.log(data); // see response in the console
// add title of recipes in a list
$.each(data.recipes, function(key, value) {
$('#result').append($('<li></li>').text(value.title));
});
}
);
});
});
</script>
routes.php just for demo you can move this to your controller
Route::post('recipes', function() {
$apiKey = "yourAPIkey";
$search = \Request::get('search');
// insert search and API key in URL
$apiUrl = "http://food2fork.com/api/search?key=" . $apiKey . "&q=". $search ;
// get the content of the file
//header('Content-Type: application/json');
$contentSearch = json_decode(file_get_contents($apiUrl));
return response()->json($contentSearch);
});
I'm guessing as an alternative you could use JSONP, but I'm new to JSONP and struggled to get it working with food2fork's api. Perhaps research JSONP and see if it's what you want. Example of JSONP with JQuery: https://learn.jquery.com/ajax/working-with-jsonp/

Ajax Search with pagination [Laravel]

I've read both https://gist.github.com/tobysteward/6163902 & AJAX pagination with Laravel but it seems I have a different problem so anyway.
Long story short: When I search, the right data gets fetched and the ajax works "display data, no refresh" only for the first page, but from next page on the page refreshes, so how to make an ajax call that loop through the returned data and display it according to each page?
Also how to add the search query to the URL, currently when the data gets fetched, the URL doesn't update, instead it stays on its current state (i.e. index?page=3).
search form
{{ Form::open(['route' => 'search', 'method' => 'GET', 'id' => 's-form',])}}
{{ Form::text('search', null, ['id' => 'search', 'placeholder' => 'Search For ...']) }}
{{ Form::submit(Go) }}
{{ Form::close() }}
search controller
public function search() {
$input = Input::get('search');
$posts = Post::where('title','LIKE',$input)->paginate(4);
if (Request::ajax()) {
return View::make('posts.search')->withPosts($posts);
}
return View::make('posts.index')->withPosts($posts);
}
search view
#forelse ($posts as $post)
// do stuff
#endforeach
<nav>{{ $posts->appends(Request::except('page'))->links() }}</nav>
the js
$('#s-form').submit(function(e)
{
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
data:{
search: $('#search').val()
},
success: function(data){
$('#result').html(data);
}
});
});
This is all it needed:
$(document).ajaxComplete(function() {
$('.pagination li a').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data) {
$('#result').html(data);
}
});
});
});
Now I just need to update the URL according to each page.

Resources