why are my dropdown is not showing in laravel 5 - php

This is my playingcards-advance (view page):
<h5>Country:</h5>
<select class="productcategory put" id="prod_cat_id">
<option value="0" disabled="true" selected="true">-Select-</option>
#foreach($prod as $cat)
<option value="{{$cat->id}}">{{$cat->product_cat_name}}</option>
#endforeach
</select>
<h5>State:</h5>
<select class="productname put">
<option value="0" disabled="true" selected="true">Select State</option>
</select>
<h5>City:</h5>
<select class="city put">
<option value="0" disabled="true" selected="true">Select City</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document).on('change', '.productcategory', function () {
// console.log("hmm its change");
var cat_id = $(this).val();
// console.log(cat_id);
var div = $(this).parent();
var op = " ";
$.ajax({
type: 'get',
url: '{!!URL::to('findProductName')!!}',
data: {'id': cat_id},
success: function (data) {
//console.log('success');
//console.log(data);
//console.log(data.length);
op += '<option value="0" selected disabled>Select City</option>';
for (var i = 0; i < data.length; i++) {
op += '<option value="' + data[i].id + '">' + data[i].productname + '</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 = "";
$.ajax({
type: 'get',
url: '{!!URL::to('findcity')!!}',
data: {'id': prod_id},
dataType: 'json',//return data will be json
success: function (data) {
console.log('success');
console.log(data);
op += '<option value="0" selected disabled>choose city</option>';
for (var i = 0; i < data.length; i++) {
op += '<option value="' + data[i].id + '">' + data[i].city + '</option>';
}
a.find('.city').html(" ");
a.find('.city').append(op);
},
error: function () {
}
});
});
});
</script>
This is my Route code:
Route::get('/playingcards-advance', 'PagesController#prodfunct');
Route::get('/findProductName', 'PagesController#findProductName');
Route::get('/findPrice', 'PagesController#findPrice');
Route::get('/findcity', 'PagesController#findcity');
This is PagesController code
public function prodfunct()
{
$prod = ProductCat::all();//get data from table
return view('playingcards-advance', compact('prod'));//sent data to view
}
public function findProductName(Request $request)
{
//if our chosen id and products table prod_cat_id col match the get first 100 data
//$request->id here is the id of our chosen option id
$data = Product::select('productname', 'id')->where('prod_cat_id', $request->id)->take(100)->get();
return response()->json($data);//then sent this data to ajax success
}
public function findcity(Request $request)
{
//if our chosen id and products table prod_cat_id col match the get first 100 data
//$request->id here is the id of our chosen option id
$q = City::select('city', 'id')->where('state_id', $request->id)->take(100)->get();
return response()->json($q);//then sent this data to ajax success
}
The problem is that I'm not able to display state and city but I'm able to display country
I have also made model of all table
why it is not displaying state and city in the code
when I click on console and try to select country as America it is giving this error GET http://localhost/tmcards2/public/findProductName?id=1 500 (Internal Server Error)
The problem is that I'm not able to display state and city but I'm able to display country
I have also made model of all table
why it is not displaying state and city in the code
when I click on console and try to select country as America it is giving this error GET http://localhost/tmcards2/public/findProductName?id=1 500 (Internal Server Error)
The problem is that I'm not able to display state and city but I'm able to display country
I have also made model of all table
why it is not displaying state and city in the code
when I click on console and try to select country as America it is giving this error GET http://localhost/tmcards2/public/findProductName?id=1 500 (Internal Server Error)
why it is not displaying state and city in the code
when I click on console and try to select country as America it is giving this error GET http://localhost/tmcards2/public/findProductName?id=1 500 (Internal Server Error)

Related

Unable to save table column value from dropdown in Laravel

I am using Laravel 7 and PHP 7.4.
I' m trying to make a dependent dropdown into my form using ajax. I'm sending the column_id and column in ajax response to my dropdown. My dropdown is working absolutely fine but there is mess with my either database query or ajax response. My dropdown shows the values of column but when I try to save into database, it only saves the "Id" of column not the value.
I just wanted to send the column_id and column both to my dropdown but only save the value into database.
Blade
<form action="{{route('form_for_private_sellers')}}>
<div class="form-group">
<select name="make" id="make" data-dependent="model">
<option value="">Select Make</option>
<option value="254">Abarth</option>
</select>
</div>
<div class="form-group">
<select name="model" id="model">
<option selected value="">Select Model*</option>
</select>
</div>
</form>
Javascript
$("#make").change(function()
{
var id=$(this).val();
var make_id = id;
var dependent = $(this).data('dependent');
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('fetchModel') }}",
method:"POST",
data:{make_id:make_id, _token:_token,dependent:dependent},
success:function(result)
{
$('#'+dependent).html(result);
}
});
});
Controller
public function fetchModel(Request $request)
{
$get_make_id = $request->get('make_id');
$dependent = $request->get('dependent');
$fetch_model = DB::table('auto_databases_one')
->select('model','model_id')
->distinct()
->where('make_id', '=', $get_make_id)
->where(function ($query) {
$query->orWhere('is_active', '=', '1');
})
->orderBy('model', 'ASC')
->get();
$show_model = '<option value="">Select ' . ucfirst(dependent) . '</option>';
foreach ($fetch_model as $row) {
$show_model .= '<option value="' . $row->model_id . '">' . $row->model . '</option>';
}
echo $show_model;
}
public function form_for_private_sellers(Request $request)
{
$store_seller = new Sellers();
$store_seller->make = $request['make'];
$store_seller->model = $request['model'];
}
I assume there is a button with id="save".
$("#save").click(function(e)
{
e.preventDefault();
const make = $("#make option:selected").val();
const model = $("#model option:selected").val();
const _token = $('input[name="_token"]').val();
$.ajax({
url:"{{route('form_for_private_sellers')}}",
method:"POST",
data:{make, _token, model},
success:function(result)
{
console.log('all done');
}
});
});
public function form_for_private_sellers(Request $request)
{
$store_seller = new Sellers();
//you may need to adjust this part as I do not know your properties called.
$store_seller->make = $request->make;
$store_seller->model = $request->model;
$store_seller->save();
}

Dependent Drop Down Jquery option list JSON error

Guys I am very new in Jquery and Json trying, I am trying to create a Dependent Option list with Jquery but it's not working. I am expecting your kind help.
here is my HTML code..
<div class="form-group">
<label for="categoriesId">
Categories</label>
<select class="form-control" id="categoriesId" name="categoriesId">
<option selcted="">Select
Categories</option>
<?php
getCat();
?>
</select>
</div>
and my fetchProductDta.php page code is here
<?php
require_once 'db_connect.php';
if(isset($_POST['cid'])){
$sql = "SELECT product_id, product_name
FROM product WHERE categories_id = '". $cid
."'";
$result = $connect->query($sql);
while($product = $productData->fetch_array()) {
echo "<option value='".$product['product_id']."'>
".$product['product_name']."</option>";
}
}
?>
My Jquery Code is here
$(document).ready(function () {
$("#categoriesId").change(function () {
var cid = $("#categoriesId").val();
$.ajax({
url: 'fetchProductData.php',
method: 'POST',
data: 'cid' + cid
.done(function (product) {
console.log(product);
product = json.parse(product);
product.forEach(function (products) {
$('#product').appned();
});
});
});
In your jquery you have mistakes , first of all you are getting html response from server as Nigel Ren said.So,to get that you don't need to use json.parse .Also i didn't find any id with name product in your html code.and there is no appned function in jquery .So,make below changes in your code to make it worked.
$(document).ready(function () {
$("#categoriesId").change(function () {
var cid = $("#categoriesId").val();
$.ajax({
url: 'fetchProductData.php',
method: 'POST',
data: {cid : cid },
success:function(data){
$("#product").html(data);//here response from server will be display in #product
}
});
});

Jquery plugin Chosen not working on AJAX Call

I have two drop downs. First one contains mobile networks MTN , VODACOM , TELKOM and the second is a chosen multiselect dropdown which should contain data (cell numbers) populated via AJAX based on the mobile network above. but it is not firing after an AJAX call.
<div id="network" class="form-group required">
<label class="control-label">Mobile Network</label>
<select class="form-control" id="network" name="network">
<option id="MTN" value="MTN">MTN</option>
<option id="VODACOM" value="VODACOM">VODACOM</option>
<option id="TELKOM" value="TELKOM">TELKOM</option>
</select>
</div>
And the second one contain cell numbers based on what is selected from above. and the dropdown uses the Chosen Plugin
<div id="cellNumber" class="form-group required">
<label class="control-label">Select SIMs</label>
<select multiple class="chosen-select form-control" id="cellNumber" name="cellNumber[]">
</select>
</div>
On the page i do this
<script>
$("select.chosen-select").chosen(); //Initializing the plugin
$('select#network').change(function () {
var id = $('select#network').children(':selected').attr('id');
if(id != " "){
localStorage.clear();
AJAXCallNumbersByCarrier(id); //AJAX Call
}
});
</script>
And this is the AJAX
function AJAXCallNumbersByCarrier(data) {
var url = "/number/" + encodeURI(data) + "/carrier";
var type = "GET";
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"').attr('content')
}
});
jQuery.ajax({
url: url,
type: type,
data: {
"_token": $('meta[name="csrf-token"').attr('content')
},
beforeSend: function () { },
success: function (data) {
try {
var count = data.length;
if (count > 0) {
var id = $('#cellNumber').attr('id');
$('select#cellNumber').empty();
var numbers = "<option value='' hidden=''>[Select SIMs]</option>";
for (var index = 0; index < count; index++) {
details = data[index];
id = details['cellnumber'];
cellnumber = details['cellnumber'];
simserial = details['simserial'];
realm = details['apnname'];
numbers += '<option id="' + id + '" value="' + cellnumber + '">'+'[ '+ cellnumber + ' ] [ ' + simserial + ' ] [ ' + realm + ' ]' + '</option>';
}
$('select#cellNumber').append(numbers);
$('div#cellNumber').show();
}else{
$('div#ErrorMessage').empty();
$('div#ErrorMessage').append("No numbers available for the selected customer");
$('div#ErrorMessage').show();
$('div.alert').not('.alert-important').delay(3000).fadeOut(350);
$('select#cellNumber').empty();
$('select#cellNumber').append("<option value'' hidden=''>[No numbers available for the selected customer]</option>");
$('div#cellNumber').show();
}
} catch (err) {
alert("Error running JS code from module: AJAXCallNumbersByCarrier");
}
},
error: function (url, jqXHR, textStatus, errorThrown) {
alert("url: " + url + " error: " + jqXHR.responseText + " status: " + textStatus + " errorThrown: " + errorThrown);
},
complete: function () { }
});
}
When i remove the $("select.chosen-select").chosen(); it works fine as a normal HTML multi select dropdown. The issue is the chosen. It is not firing. Data is empty. Please help.
try to reinitialize the chosen in the success function like
success:function(data){
// your code here
$('select#cellNumber').append(numbers);
$("select.chosen-select").chosen();
$('div#cellNumber').show();
}
it solved once i face the same issue.
Hope this helps.
I used Select2 instead. works well.

How to get json encode data into dropdown field in php?

<script>
$(document).ready(function(){
$("#region").change(function(){
region = $(this).val()
$.ajax({
type:"POST",
data:{"region":region},
url:"get-city.php",
success:function(data){
alert(data);
//$("#city").html(data);
//$("#state").html(data);
}
});
});
});
</script>
<select name="region" id="region" >
<option value="">Select Region</option>
<?php
$sql = mysqli_query($con, "SELECT * FROM `region`");
while($row = mysqli_fetch_array($sql))
{
?>
<option value="<?php echo $row['heading_text']; ?>"><?php echo $row['heading_text']; ?></option>
<?php
}
?>
</select>
<select name="state" id="state">
<option value="">Select Region State</option>
</select>
<select name="city" id="city">
<option value="">Select Region City</option>
</select>
get-city.php
<?php
error_reporting(0);
include('dbase.php');
$region = $_POST['region'];
$sql = "select * from region_data where heading_text='".$region."'";
$results = mysqli_query($con,$sql);
while($rows = mysqli_fetch_assoc($results))
{
$data[] = array(
'state' => $rows['state'],
'city' => $rows['name']
);
}
echo json_encode($data);
?>
In this code I have created simple dropdown one is for region where I change its value by id as you can see in jquery code. Now, As you can see in get-city.php file I have encode data via json_encode function which work fine. But problem is I am not able to show data in state and city drop down in php. My json_encode data look like:
[{"state":"","city":"delhi"},{"state":"","city":"agra"},{"state":"","city":"varanasi"},{"state":"","city":"haridwar"},{"state":"","city":"dharamshala"},{"state":"","city":"srinagar"},{"state":"","city":"mussoorie"},{"state":"","city":"amritsar"},{"state":"","city":"shimla"},{"state":"","city":"kullu manali"},{"state":"","city":"assam"},{"state":"","city":"meghalaya"},{"state":"","city":"arunachal pradesh"},{"state":"","city":"manipur"},{"state":"","city":"nagaland"},{"state":"","city":"J AND K"},{"state":"38","city":"Saharanpur"}]
So, How can I get value in dropdown? Please help me.
Thank You
You'll have to use parseJSON in jQuery to decode the JSON data and then append() the option values to city and state select tags.
<script>
$(document).ready(function(){
$("#region").change(function(){
region = $(this).val()
$.ajax({
type:"POST",
data:{"region":region},
url:"get-city.php",
success:function(data){
var obj = $.parseJSON(data);
$.each(obj, function() {
$("#city").append('<option value="'+this['city']+'">'+this['city']+'</option>');
$("#state").append('<option value="'+this['state']+'">'+this['state']+'</option>');
});
//$("#city").html(data);
//$("#state").html(data);
}
});
});
});
</script>
If you need to get back a JavaScript object from a JSON string, you are looking for JSON.parse().
I did not got exactly how you want to display data, but as far as I understand you are looking for a way to populate the dropdowns, so I will show you only for the city part...for all the other dropdowns the flow is the same.
Assuming you have all the cities in the cities variable after the AJAX call (and after the JSON.parse call if needed):
let cities = [{"state":"","city":"delhi"},{"state":"","city":"agra"},{"state":"","city":"varanasi"},{"state":"","city":"haridwar"},{"state":"","city":"dharamshala"},{"state":"","city":"srinagar"},{"state":"","city":"mussoorie"},{"state":"","city":"amritsar"},{"state":"","city":"shimla"},{"state":"","city":"kullu manali"},{"state":"","city":"assam"},{"state":"","city":"meghalaya"},{"state":"","city":"arunachal pradesh"},{"state":"","city":"manipur"},{"state":"","city":"nagaland"},{"state":"","city":"J AND K"},{"state":"38","city":"Saharanpur"}];
cities.map(function(item, index) {
// let's build an <option> element
const city = jQuery("<option>", {value: item.city, text: item.city})
// let's add the <option> element to the right <select>
jQuery("#city").append(city);
});
this is one of the solution. You can search more for dependent dropdown
use value.city and vvalue.state as you want, or key as option value , its upto you, i just showed how you get values
$.ajax({
url:"get-city.php",
data:{"region":region},
type: "POST",
success: function(data) {
$('select[name="city"]').empty();
$.each( JSON.parse(data), function(key, value) { // or use data without JSON.parse(data)
$('select[name="city"]').append('<option value="'+ value.state +'">'+ value.city +'</option>');
});
}
});
Inside your success section:
success:function(data){
for(let i = 0; i < data.length; i++){
$('select[name="city"]').append('<option value="'+ data[i].city +'">'+ data[i].city +'</option>');
}
}

How can I poupulate a hidden form field with a value from a dropdown?

I have these:
$(document).ready(function() {
getRequestCategories();
$('#requestCategory').change(function() {
getRequestDescriptions( $(this).val() );
});
});
function getRequestCategories() {
$.ajax({
url: 'getCategories.php',
dataType: 'json'
})
.done(function(categoryInfo) {
$(categoryInfo).each(function(i, category) {
$('<option>').val(category.RequestCategoryDisplay).text(category.RequestCategoryDisplay).appendTo( $('#requestCategory') );
})
});
}
function getRequestDescriptions(requestCategory) {
$.ajax({
url: 'getDescriptions.php',
dataType: 'json',
data: { requestCategory: requestCategory }
})
.done(function(descriptionInfo) {
$(descriptionInfo).each(function(i, description) {
$('<option>').val(description.RequestDescriptionDisplay).text(description.RequestDescriptionDisplay).appendTo( $('#description') );
})
});
}
Category
<select name="requestCategory" id="Category" style="width:250px;font-size:10pt;" class="changeable" data-summary="summCategory">
<option value=""></option>
</select>
Description
<select name="description" id="description" style="width:250px;font-size:10pt;" class="changeable" data-summary="summSubCategory">
<option value=""></option>
</select>
How it works currently:
When you select a value from the Category dropdown, all the values associated with your selection are automatically into the description dropdown.
This works fine.
However, we have a new requirement to populate the following hidden form field with user's selection from the description dropdown:
<input name="RequestID" id="RequestID" type="text" width="300" value="" class="changeable" />
In other words, once the description dropdown is populated with values based on selection from Category dropdown, then when a user selects one of the values from the description dropdown, the accompanying value of RequestID should be saved into a hidden form field.
I tried modifying the getDescriptions function but I am not getting the correct values.
Each value I select from the description dropdown gives me same values for RequestID.
Can you please see what I am doing wrong?
Thanks so much in advance.
function getDescriptions(requestCategory) {
$.ajax({
url: 'getDescriptions.php',
dataType: 'json',
data: { requestCategory: requestCategory }
})
.done(function(descriptionInfo) {
// get number of items in array given by php
var Desc_count = descriptionInfo.length;
// loop request descriptions
for (var i = 0; i < Desc_count; i += 1) {
// append an <option> tag to your <select>
$('#description').append('<option value="' + descriptionInfo[i].RequestID + '">' + descriptionInfo[i].RequestDescriptionDisplay + '</option>');
}
// Listen for the value of the <select> to change
$('#description').on('change', function () {
// get the value of the selected option ,the value is the descriptionInfo[i].RequestID
var value = $( "#description option:selected").val();
// Set the value of the hidden fields based on the <select>'s ID choosing the corret array element
$('input[name="RequestID"]').val(value);
});
});
}
Very strange this isnt working.. is your on change event happening in $(document).ready() ?
I try to help:
instad of your $('#description').on('change', function () { event try this:
$(document).ready(function() {
$('#description').change(function() {
$('#RequestID').val($(this).val());
});
});
if this doesnt work try:
$(document).ready(function() {
$('#description').live('change', function() {
$('#RequestID').val($(this).val());
});
});

Categories