I want when I select a category to show me all the subcategories for that specific category, but this is the error that I am getting:
GET http://localhost:8000/shto/njesin-stratigrafike?sektori+id=III 500
(Internal Server Error)
Here is the html code for dropdown lists
<select class="form-control" name="selected_sector2" id="category">
<option value="blank">Zgjedh sektorin</option>
#foreach($sektorat['sektorat2'] as $sektori2)
<option name="sektori">
{{ $sektori2->sektori_nr }}
</option>
#endforeach
</select>
here is the Route code
Route::get('shto/njesin-stratigrafike', 'NjesiteStratigrafikeController#shtoNjesiStratigrafike');
here is the Controller code
class NjesiteStratigrafikeController extends Controller
{
public function shtoNjesiStratigrafike(){
$selected_sector = Input::get('selected_sector2');
$sector_id = Sektori::where('sektori_nr',$selected_sector)
->value('sektori_id');
$kuadratet = Kuadrati::where('sektori_id_fk', '=' ,$sector_id)->get();
return Response::json($kuadratet);
}
}
Here is the ajax code
<script type="text/javascript">
$('#category').on('change', function(e) {
var sektori_id = e.target.value;
// Ajax
$.get('/shto/njesin-stratigrafike?sektori+id=' + sektori_id, function(data) {
// Success data
$('#subcategory').empty();
$('#subcategory').append(' Please choose one');
$.each(data, function(index, subcatObj) {
$('#subcategory').append('' + subcatObj.subcategory_name + '</option>');
});
});
});
</script>
you can see following code
in view
<div class="form-group m-r-10">
<label for="exampleInputName2">Category</label>
<select class="form-control select2 productcategory" name="productcategory">
<option value="0" disabled="true" selected="true">
Product Category
</option>
#foreach($category as $c)
<option value="{{$c->id}}">{{$c->type_name}}</option>
#endforeach
</select>
</div>
<div class="form-group m-r-10">
<label for="exampleInputName2">Name</label>
<select class="form-control productname" name="productname">
<option value="0" disabled="true" selected="true">Product Name</option>
#foreach($products as $p)
<option value="{{$p->id}}">{{$p->name}}</option>
#endforeach
</select>
</div>
in ajax
<script type="text/javascript">
$(document).ready(function(){
/*--------------------------------------------------------------------------------------------------------------
* Click Add more Product
*/
$(document).on('change','.row .card_prod .productcategory',function () {
console.log("changeproduct category");
var div=$(this).parent().parent().parent().parent();
var category_id=$(this).val();
console.log(category_id);
var op="";
$.ajax({
type:'GET',
url:'{!!URL::route('findProductName')!!}',
// dataType:'json',
data:{id:category_id},
success:function(data)
{
//tr.find('.price').val(data.price);
console.log(data);
for(var i=0;i<data.length;i++){
console.log(data[i].name);
// console.log(i);
op+='<option value="'+data[i].id+'">'+data[i].name+'</option>';
}
// div.find('.productname').css('background-color','pink');
div.find('.productname').html("");
div.find('.productname').append(op);
},
error:function(msg){
console.log(msg);
console.log("error");
}
});
});
// document DOM end
</script>
in route
Route::get('/findProductName',array('as'=>'findProductName','uses'=>'InventoryController#findProductName'));
in controller
public function findProductName(Request $request)
{
$data=Product::select('name','id')->where('type_fk_id',$request->id)->take(100)->get();;
return response()->json($data);
}
Related
I am trying to build the form repeater where ID and Datapoint are select tag. When I select ID than Datapoint will be taken from AJAX response and appended to option. In the picture you can see when I call for select for the first time the datapoint (select tag) is showing the values but when trying to add another the datapoint there is no response.
<form method="post" class="repeater" enctype="multipart/form-data">
<div data-repeater-list="samplernetwork">
<div data-repeater-item="data-repeater-item" class="row">
<div class="mb-3 col-lg-2">
<label for="id">ID</label>
<select class="form-control" name="id" id="id">
<option></option>
{% for id in id %}
<option value="{{id.id}}">{{id.id}}</option>
{% endfor %}
</select>
</div>
<div class="mb-3 col-lg-2">
<label for="datapoint">Datapoint</label>
<select class="form-control" name="datapoint" id="datapoint"></select>
</div>
<div class="col-lg-2 align-self-center">
<div class="d-grid">
<input data-repeater-delete="data-repeater-delete" type="button" class="btn btn-primary" value="Delete"/>
</div>
</div>
</div>
</div>
<input data-repeater-create="data-repeater-create" type="button" class="btn btn-success mt-3 mt-lg-0" value="Add"/>
</form>
<script src="/libs/jquery.repeater/jquery.repeater.min.js"></script>
<script src="/js/pages/form-repeater.int.js"></script>
<script>
$("#id").on('change', function (e) {
var consti = $(this).val()
console.log(consti)
if (consti === "") {
$('#datapoint').find('option').remove()
} else if (consti != null) {
var url = '{{path(' app_info ',{' id ':' ReplaceMeWithCorrectValue '})}}';
url = url.replace("ReplaceMeWithCorrectValue", consti);
var options = ""
$.ajax({
type: "POST",
url: url,
success: function (response) {
var information = JSON.parse(response)
for (let item in information) {
options += `<option value=${item}>${item}</option>`;
}
$("#datapoint").html(options);
}
});
}
});
</script>
<script src="/js/app.js"></script>
The solution of the code
<form id="repeater-form">
<div class="repeater">
<div data-repeater-list="group-a">
<div data-repeater-item>
<select name="field-1" class="field-1">
<option value="">Select an option</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<select name="field-2" class="field-2" disabled>
<option value="">Select an option</option>
</select>
<button data-repeater-delete type="button">Delete</button>
</div>
</div>
<button data-repeater-create type="button">Add</button>
</div>
<input type="submit" value="Submit" />
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.repeater/1.2.1/jquery.repeater.min.js"></script>
<script>
$(document).ready(function () {
$('.repeater').repeater({
initEmpty: false,
show: function () {
$(this).slideDown();
},
hide: function (deleteElement) {
if(confirm('Are you sure you want to delete this element?')) {
$(this).slideUp(deleteElement);
}
}
});
$(document).on('change', '.field-1', function() {
var selectedValue = $(this).val();
var $field2 = $(this).closest('div[data-repeater-item]').find('.field-2');
$.ajax({
type: 'GET',
url: 'options.php',
data: {'value': selectedValue},
success: function (response) {
var options = JSON.parse(response);
var select = $field2;
select.empty();
select.append('<option value="">Select an option</option>');
for (var i = 0; i < options.length; i++) {
select.append('<option value="' + options[i].value + '">' + options[i].text + '</option>');
}
select.prop('disabled', false);
}
});
});
$('#repeater-form').submit(function (e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'server-script.php',
data: formData,
success: function (response) {
alert(response);
}
});
});
});
</script>
i'm trying to show new select input contains (states) options, when user select specific option a (USA) country, and when select another country non (USA) don't show the states select options i want in this case still hidden.
Route
Route::get('/ajax-form', [AjaxController::class, 'index'])->name('ajax.index');
Route::get('/getState/{id}', [AjaxController::class, 'getState'])->name('ajax.state');
Controller
class AjaxController extends Controller
{
public function index()
{
$countries['data'] = Country::orderby('name')
->select('id', 'name')
->get();
return view('ajax.index', compact('countries'));
}
public function getState($countryId = 0)
{
$states['data'] = State::orderby('name')
->select('id', 'name')
->where('country_id', $countryId)
->get();
return response()->json($states);
}
Blade form with script:
#extends('layouts.app')
#section('form')
<form>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputCountry">Country</label>
<select class="country" id="inputCountry" class="form-control">
<option selected>Choose...</option>
#if ($countries['data'] && $countries['data']->count() > 0)
#foreach ($countries['data'] as $country)
<option value="{{ $country->id }}">{{ $country->name }}</option>
#endforeach
#endif
</select>
</div>
</div>
<div id="stateShow" class="form-row hidden">
<div class="form-group col-md-6">
<label for="inputState">State</label>
<select id="inputState" class="form-control">
<option value='0' selected>Choose...</option>
</select>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
#stop
#section('script')
<script type="text/javascript">
$(document).ready(function () {
$('#inputCountry').change(function() {
var id = $(this).val();
// Empty the States dropdown without first
$('#stateShow').show();
$('#inputState').find('option').not(':first').remove();
// ajax request
$.ajax({
url: 'getState/' + id,
type:'get',
dataType: 'json',
success: function(response) {
var len = 0;
if(response['data'] != null) {
len = response['data'].length;
}
if(len > 0) {
// Read data in the state option that related with country
for(var i = 0; i < len; i++) {
var id = response['data'][i].id;
var name = response['data'][i].name;
var option = "<option value='" + id + "'>" + name + "</option>";
$('#inputState').append(option);
}
}
}
});
});
});
</script>
#stop
the above script doing, when i select any country, the hidden (states) select is shown, i want it shows only when i select (USA) and non that still hidden
could you help me
In your inputCountry select-box i am assuming {{ $country->name }} is country name so you can use $(this).find("option:selected").text() to get this value and then compare it with USA if they are equal show your div else hide it.
Demo Code :
$('#inputCountry').change(function() {
var id = $(this).val();
var text = $(this).find("option:selected").text().trim() //get text
if (text == "USA") {
$('#stateShow').show(); //show
$('#inputState').find('option').not(':first').remove();
//your ajax call put here ....
} else {
$('#stateShow').hide(); //hide
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputCountry">Country</label>
<select class="country" id="inputCountry" class="form-control">
<option selected>Choose...</option>
<option value="{{ $country->id }}">Abc</option>
<option value="{{ $country->id }}">USA</option>
</select>
</div>
</div>
<div id="stateShow" class="form-row hidden">
<div class="form-group col-md-6">
<label for="inputState">State</label>
<select id="inputState" class="form-control">
<option value='0' selected>Choose...</option>
</select>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
i have an appended, there a selectbox with 2 textbox
first the selectbox will selecting an item, after on change, it will set all the textbox with data based on selected.
my select option calling data from database array $data.
this is my ajax code
function getBarang(val) {
$.ajax({
url: baseurl + "JSON/getBarang",
// url: baseurl + "JSON/getVal" + val,
type:"POST",
data:{"get_barang":val},
dataType:"JSON",
success:function(data){
$('#harga_jual').val((data[0].harga_jual));
$('#stock_sisa').val((data[0].stock_sisa));
}
});
}
this is my form
echo '<select name="barang[]" id="barang-'.$row.'" class="s2barang form-control" onchange="getBarang(this.value)">';
echo (isset($dBarang->id_barang)) ? '<option value="' . $dBarang->id_barang.'">' . $dBarang->nama_barang . '</option>' : '';
echo ' </select> ';
echo '
<input type="text" class="form-control" name="stock_sisa" id="stock_sisa">
<input type="text" class="form-control" name="harga_jual" id="harga_jual">
lets pass about query data, because its worked.
and this is my view as result
my second textbox not working, pls help me, thanks
Edited:
Let me explain more.
the target is textbox stock sisa, and textbox harga_jual
the $dBarang created like this, $row just like $i=0, for cheching last data on database
$dataBarang = $this->m_db->getDataWhere("v_pembelian_detail","id_pembelian","'$id_p' ORDER BY id_pembelian_detail");
$dataBarang = (empty($dataBarang)) ? [''] : $dataBarang;
foreach ($dataBarang as $dBarang)
{
You can pass this as well inside your function where this refer to current select-box where change has been taken place. Then , using this you can use $(el).closest('.outer').find('.harga_jual').. to add input values to required inputs only.
Demo Code :
//just for demo..
var data = [{
"harga_jual": "soemthing",
"stock_sisa": "soemthing1"
}]
function getBarang(val, el) {
/*$.ajax({
url: baseurl + "JSON/getBarang",
// url: baseurl + "JSON/getVal" + val,
type: "POST",
data: {
"get_barang": val
},
dataType: "JSON",
success: function(data) {*/
//get closest div > get input add value there..
$(el).closest('.outer').find('.harga_jual').val(data[0].harga_jual);
$(el).closest('.outer').find('.stock_sisa').val(data[0].stock_sisa);
/* }
});*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--add sme outer div-->
<div class="outer">
<select name="barang[]" id="barang-'.$row.'" class="s2barang form-control" onchange="getBarang(this.value ,this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control stock_sisa" name="stock_sisa">
<input type="text" class="form-control harga_jual" name="harga_jual">
</div>
<div class="outer">
<select name="barang[]" id="barang-'.$row.'" class="s2barang form-control" onchange="getBarang(this.value ,this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control stock_sisa" name="stock_sisa">
<input type="text" class="form-control harga_jual" name="harga_jual">
</div>
<div class="outer">
<select name="barang[]" id="barang-'.$row.'" class="s2barang form-control" onchange="getBarang(this.value ,this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control stock_sisa" name="stock_sisa">
<input type="text" class="form-control harga_jual" name="harga_jual">
</div>
this is what i get from changing my id to class
function getBarang(val) {
$.ajax({
url: baseurl + "JSON/getBarang",
// url: baseurl + "JSON/getVal" + val,
type:"POST",
data:{"get_barang":val},
dataType:"JSON",
success:function(data){
$('.harga_jual').val((data[0].harga_jual));//before #harga_jual
$('.stock_sisa').val((data[0].stock_sisa));//before #stock_sisa
}
});
}
but the data seem the last selected and change to all :(
i want it each selected
I have a dropdown list with 5 options, whenever I click the submit button in the modal, the value posted to the controller is not the one I had selected.
Here is my view code
<div class="form-group">
<div class="col-md-4">
<select class="form-control" name="procode" id="procode" >
<option value="AOC">AOC</option>
<option value="ATN">ATN</option>
<option value="AOC">APS</option>
<option value="ATN">ADS</option>
<option value="AOC">ATW</option>
<option value="ATN">ATB</option>
</select>
</div>
</div>
And my ajax code for submiting the data to controller is here
var url;
url = "<?php echo site_url('person/ajax_add_claim')?>";
$.ajax({
url : url,
type: "POST",
data: $('#formclaim').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status)
{
$('#modal_form').modal('hide');
$('#modal_form').removeData();
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error');
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
}
}
$('#btnSave').text('save');
$('#btnSave').attr('disabled',false);
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#btnSave').text('save');
$('#btnSave').attr('disabled',false);
}
});
This is a silly question to answer. But here you go:
<div class="form-group">
<div class="col-md-4">
<select class="form-control" name="procode" id="procode" >
<option value="AOC">AOC</option>
<option value="ATN">ATN</option>
<option value="APS">APS</option>
<option value="ADS">ADS</option>
<option value="ATW">ATW</option>
<option value="ATB">ATB</option>
</select>
</div>
</div>
Do you notice the difference?
The option in your dropdown contains similar values, that might be the cause of the problem.
<option value="AOC">AOC</option>
<option value="ATN">ATN</option>
<option value="AOC">APS</option>
<option value="ATN">ADS</option>
<option value="AOC">ATW</option>
<option value="ATN">ATB</option>
Try replacing the values with some other data. Just to test, whether the code is working or not.
Show us a bit of controller code to see what and how you are displaying the dropdown data.
Can you please share your controller function and reload_table function of Javascript. i think you are not returning accurate data from Controller function. You should use like this.
$drop_downdata = $this->db->function(your db query);
/* you pass this data to view like this create a page with this name dropdown_page.php */
$dropdown_view['page'] = $this->load->view('dropdown_page',array('data'=>$drop_downdata),TRUE);
$this->output->set_content_type('application/json')->set_output(json_encode($dropdown_view));
View Page dropdown_page.php
<?php foreach($data as $value): ?>
<li><?=$value->column_name?></li>
<?php endforeach; ?>
you will simple get this Drop down in this way
`$("#dropdown_id or class").html(response.page)`.
It will show your dropdown according to your request
I have two selects, the second one is hidden and it should be shown if the first select has been changed, I checked it through on('change', function(){ ... and it is working so far. I've checked and also showed a console.log when the first select box is changed.
The main problem here is when I picked a option from the first select box, it should send some request using AJAX. I've sent some request to fetch_sections.php and it should append or add data in my second select box.
This is my updated script:
<script>
$(document).ready(function() {
$('select').material_select();
$('#school-list').on('change', function() {
$.ajax({
url: 'fetch_sections.php',
type: 'post',
dataType: 'html',
data: {parent: $(this).val() },
success: function(data)
{
$('#section-list').empty();
$('#section-list').html(data);
console.log(data);
}
});
$('#hideThis').show("slow");
});
});
</script>
This is my fetch_sections.php (working, checked with PostMan):
<?php
require '../assets/php/init.php';
if ($_POST)
{
$schoolID = Essentials::sanitize($_POST['parent']);
$fetchSQL = "SELECT `sectionid`, `name` FROM `sections` WHERE schoolid = ?";
$fetch = $conn->prepare($fetchSQL);
$fetch->execute([$schoolID]);
$fetchRes = $fetch->fetchAll(PDO::FETCH_ASSOC);
if(!$fetchRes) {
echo '
<option value="" disabled selected>Unfortunately, there is no section here.</option>
';
} else {
foreach ($fetchRes as $section)
{
echo '
<option value="'.$section['sectionid'].'"">'.$section['name'].'</option>
';
}
}
}
This is my select HTML also updated:
<div class="row margin">
<div class="input-field col s12">
<select id="school-list" name="school-list">
<option value="" disabled selected>Choose your school</option>
...
</select>
<label>School</label>
</div>
</div>
<div class="row margin" id="hideThis" style="display:none">
<div class="input-field col s12">
<select id="section-list" name="section-list">
<option value="" disabled selected>Choose your section</option>
</select>
<label>Section</label>
</div>
</div>
Update [as suggested by ccKep]:
I can now see the data that I want through console.log(data), the thing that it outputs is:
<option value="9-1">9-A...</option>, now I want to add it to my main select list but it doesn't let me.
The output should be:
<select id="section-list" name="section-list">
<option value="" disabled selected>Choose your section</option>
<option value="9-1">9-A...</option>
</select>