Unable to save table column value from dropdown in Laravel - php

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

Related

How to implement a code igniter country and cities select that countries determines the city?

I am new to Ajax and JavaScript
I have a similar problem with my selects that depends on the other select but don't know where it is going wrong?
This is my Controller code- that passes the member_id to the model and it is supposed to return data back to the view selected.
public function getStates() {
$this->load->model('ReferenceModel');
$this->load->model('DailyModel');
$this->load->model('MembersModel');
$this->load->model('FundsModel');
$postData = array('member_id' => $this->request->getPost('member_id'));
$dataa = $this->FundsModel->getStates($postData);
echo json_encode($dataa);
}```
This is my AJAX Request Code
<script type='text/javascript'>
// baseURL variable
var baseURL= "<?php echo base_url();?>";
$(document).ready(function(){
// City change
$('#member_id').change(function(){
var member_id = $(this).val();
// AJAX request
$.ajax({
url:'<?=base_url()?>Historic/getStates',
method: 'post',
data: {member_id: member_id},
dataType: 'json',
success: function(response){
// Remove options
$('#id').find('Select Member').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#id').append('<option value="'+dataa['id']+'">'+dataa['fund']+'</option>');
});
}
});
});
});
</script>
Model
public function getStates($postData){
$sql = 'SELECT * FROM vw_funds_summary WHERE member_id =' .$postData['member_id'] ;
$query = $this->db->query($sql);
return $query;
}```
And My HTML Codes
<select id="member_id" name="country" class="form-control">
<option>Select Member</option>
<?php
for ($i=0;$i<$fMembers->num_rows();$i++){
echo "<option value='".$fMembers->row($i)->member_id."'>".$fMembers->row($i)->member_name."</option>";}
?>
</select>
<select class="form-control" id="id">
<option>Select Fund</option>
</select>
What is really wrong with my Code?
I have a view of both the funds and the members, that are giving the results as shown in the attached picture.
Or is there another way to do it without having to use AJAX?

How to display select option values base on the first option

I am using Codeigniter 3.1.1. I want City option to display base on the value selected with State option. Actually the City select option does not populate automatically when State option is selected. I tried to link the latest jQuery but still, it doesn't work. Your help is highly appreciated.
MyController.php
class HomeController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->database();
}
public function index() {
$states = $this->db->get("demo_state")->result();
$this->load->view('myform_view', array('states' => $states ));
}
public function myformAjax($stateID) {
$result = $this->db->where("state_id",$stateID)->get("demo_cities")->result();
echo json_encode($result);} }
View:
<select name="state" id="state" class="form-control" style="width:350px">
<option value="">---Select State---</option>
<?php foreach($states as $key => $value)
{
echo "<option value='".$value->id."'>".$value->name."</option>";
} ?>
</select>
<select name="city" id="city" class="form-control" style="width:350px"></select>
Ajax:
$(document).ready(function() {
$('select[name="state"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/MyController/myformAjax/'+stateID,
type: "POST",
dataType: "json",
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ value.id +'">'+ value.name +'</option>');
});
}
});
}else{
$('select[name="city"]').empty();
}
});
});
You've not specified what problem you face when you run your code or what is the output or what is the error, so, we've no way of knowing what the real issue is. However, I'm sharing a working code (an excerpt from my project) of what you want; I've also changed the values according to your needs.
This follows a different approach as AJAX expects HTML to be
returned and that HTML is formed in PHP controller rather than on success in jQuery and then simply added to the desired id.
AJAX
$(document).ready(function() {
$('#state').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/MyController/myformAjax/'+stateID, // your-controller-path
// sometimes relative path might not work try with base_url() instead or configure your .htaccess properly
type: "POST",
dataType: "html", // expecting html
success:function(data) {
$('#city').empty();
$('#city').html(data); // change innerHTML of id='city'
}
});
}else{
$('#city').empty(); // $('#city').html('');
}
});
});
Controller
public function myformAjax($stateID) {
$cities = $this->db->where("state_id",$stateID)->get("demo_cities")->result(); // get all the cities -- probably want to do this in model
$cityOpt = '<option value="">--Select City--</option>'; // first option -- to prevent first option from automatically selecting when submitting data
foreach($cities as $city)
{
$cityOpt .= '<option value="'.$city->id.'">'.$city->city_name.'</option>'; // concatenate the next value
}
echo $cityOpt;
}
See if it helps you.

Fetch Database Value to multiple textboxes based on dropdown value in php

I want to populate textbox values automatically from DB based on dropdown selection.....I have tried this, but after selecting dropdown the page is refreshing but the values are not populated onto textbox....need Help!!
Table
Controller:
public function isrexpense()
{
$data['query'] = $this->Isr_model->getstates();
$data['names'] = $this->Isr_model->getAllNames();
$data['query1'] = $this->Isr_model->test();
$this->load->view("header");
$this->load->view('Isr/isrexpense', $data);
$this->load->view("footer");
}
Model:
function test()
{
$this->db->select('da_hq');
$this->db->from('isr_policy_master');
$this->db->where('state', $this->input->post('state'));
$query = $this->db->get();
return $query->result();
}
View:
<select class="js-example-basic-single form-control">
<?php
foreach($names as $row)
{
echo '<option></option>';
echo '<option value="'.$row->name.'">'.$row->name.'</option>';
}
?>
</select>
<select class="state form-control" id="state" name="state">
<?php
foreach($query as $row)
{
echo '<option value="'.$row->state_code.'">'.$row->state_name.'</option>';
} ?>
</select>
<script>
$('#state').on('change', function(){
var mainselection = this.value; // get the selection value
$.ajax({
type: "POST", // method of sending data
url: "<?php echo site_url(); ?>/Isr/isrexpense",
data:'selection='+mainselection,
success: function(result)
{
$("#hqda").html(result);
}
});
});
</script>
<input id="hqda" name="hqda" class="form-control" required type="number">
Controller :
public function isrexpense()
{
$data['query'] = $this->Isr_model->getstates();
$data['names'] = $this->Isr_model->getAllNames();
$this->load->view("header");
$this->load->view('Isr/isrexpense', $data);
$this->load->view("footer");
}
public function getValFromDb()
{
$state = $this->input->post('selection');
$query1 = $this->Isr_model->test($state);
echo json_encode(array('data'=>$query1));
}
Model:
function test($state)
{
$this->db->select('da_hq');
$this->db->from('isr_policy_master');
$this->db->where('state', $state);
$query = $this->db->get();
$result = $query->result();
if(count($result)>0)
{
return $result[0]['da_hq'];
}
else
{
return '';
}
}
View :
<script>
$('#state').on('change', function(){
var mainselection = this.value; // get the selection value
$.ajax({
type: "POST", // method of sending data
url: "<?php echo site_url(); ?>/Isr/getValFromDb",
data:'selection='+mainselection,
success: function(result)
{
console.log(result); // check this in your console and if require than use JSON.parse to get value
$("#hqda").val(result.data);
}
});
});
</script>
Textboxes don't have an "innerHTML" property. If you want to set the content of a textbox, you should set its value property. In jQuery you do this using the .val() method.
Replace
$("#hqda").html(result);
with
$("#hqda").val(result);
Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
and http://api.jquery.com/val/
P.S. You may also want to take a look at what your AJAX call returns - it's not clear whether it would return the content you're looking for or not - it appears to return a whole HTML view, rather than just a single value to place into a textbox.

How to change the url of current page while making ajax request in ci?

I have created dynamic dependent dropdown list where I am selecting and option and sending request to the controller to fetch the data from database. I need to display the selected option name in the URL once the data will be fetched from the database. I am unable to do this and getting the same page url.
View:
<script type="text/javascript">
$(document).ready(function(){
/* Populate data to state dropdown */
$('#country').on('change',function(){
var countryID = $(this).val();
var countryName= $('#country option:selected').html();
// alert(countryName);
if(countryID){
$.ajax({
type:'POST',
url:'<?php echo base_url('bank/getDistrict'); ?>/'+countryName,
data:'country_id='+countryID,
success:function(data){
$('#state').html('<option value="">Select District</option>');
var dataObj = jQuery.parseJSON(data);
if(dataObj){
$(dataObj).each(function(){
var option = $('<option />');
option.attr('value', this.id).text(this.district_name);
$('#state').append(option);
});
}else{
$('#state').html('<option value="">District not available</option>');
}
}
});
}else{
$('#state').html('<option value="">Select state first</option>');
$('#city').html('<option value="">Select district first</option>');
}
});
Controller:
public function getDistrict(){
$states = array();
$country_id = $this->input->post('country_id');
if($country_id){
$con['conditions'] = array('state_id'=>$country_id);
$states = $this->Bank_model->getDistrictRows($con);
}
echo json_encode($states);
}
Model:
function getDistrictRows($params = array()){
$this->db->select('s.id, s.district_name');
$this->db->from($this->districtTbl.' as s');
//fetch data by conditions
if(array_key_exists("conditions",$params)){
foreach ($params['conditions'] as $key => $value) {
if(strpos($key,'.') !== false){
$this->db->where($key,$value);
}else{
$this->db->where('s.'.$key,$value);
}
}
}
$query = $this->db->get();
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
//return fetched data
return $result;
}
My current URL is: http://localhost/real_estate/bank
After the request I am still getting the same URL. It's not appending the name of the selected option.
I want my URL like this: http://localhost/real_estate/bank/delhi
If I am choosing delhi from the select option

why are my dropdown is not showing in laravel 5

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)

Categories