How to get the selected dropdown value on submit in Laravel? - php

In Laravel, I am trying to get the value of selected drop-down value and send it to another controller. And by using that drop-down value below values need to be changed by fetching the data from the database.
Below is the code I have tried.
<form action="{{{ url("/getDetailsBynumber/$_POST['number']") }}}" method="post">
<select name="number" id="number">
<option selected="selected">Select number id</option>
<?php
$numberArray = json_decode($number_id, true);
for ($i = 0 ; $i<=$number_count ; $i++) {
?>
<option value="<?php echo $numberArray[$i]["number_value"] ?>"><?php echo $numberArray[$i]["number_value"]; ?></option>
<?php
}
?>
</select>
<input type="submit" value="Submit">

You need to add name attribute to select tag. As a result when form submitted it will send selected value with it's name. For example:
<select name="product_id">
<option value="1">Cup</option> <!-- Suppose this option selected -->
<option value="2">Pen</option>
<option value="3">Book</option>
</select>
If you submit form, you can get selected value in your controller as follows:
public function methodName(Request $request)
{
// $request->product_id is name attribute of your select tag
print_r($request->product_id); // It will print out 1 which is value of Cup
}

<form action="{{ url("/getDetailsBynumber/") . $_POST['number'] }}" method="post">
<select name="number" id="number">
<option selected="selected">Select number id</option>
<?php
$numberArray = json_decode($number_id, true);
for ($i = 0 ; $i<=$number_count ; $i++) {
?>
<option value="<?php echo $numberArray[$i]["number_value"] ?>"><?php echo $numberArray[$i]["number_value"]; ?></option>
<?php
}
?>
</select>
<input type="submit" value="Submit">

This is my code to get state name after submit if validation fail incase then it works
on load of page you can get the country id like this
var countryid = $('#opt_country').val();
after that base on that you have to find state_id
like this
if (countryid != '')
{
$.ajax({
url: base_path + 'getstate',
type: "POST",
data: {in_country_id: countryid},
async: true,
cache: false,
success: function (statedata) {
var obj = jQuery.parseJSON(statedata);
console.log(obj);
if (obj.SUCC_FLAG == 1)
{
for (var i in obj)
{
console.log(obj);
var id = obj[i].in_state_id;
var name = obj[i].st_state_name;
if (id == stateid)
{
$("#opt_state").append("<option value='" + id + "' selected >" + name.toString() + "</option>");
} else {
$("#opt_state").append("<option value='" + id + "'>" + name.toString() + "</option>");
}
}
}
else
{
confirm('We are unable to load State');
}
},
error: function () {
alert("server error");
}
});
}
and after that you can get the state so here is my example to get state after submit the page

Related

Populating 2nd select box with the value of first select box

Currently I have 2 select boxes called Country and City. Now I've made it so that the city data is populated according to the value selected in country using AJAX. To do this I've used the following code:
edit.php:
<select name="country" onchange="getcities($(this).val())" required>
<option value="<?php echo set_value('country'); ?>">Select Country</option>
<?php if($countries) foreach($countries as $country): ?>
<option value="<?php echo $country['id']; ?>" <?php echo ($listing[0]['country'] == $country['id'])?'selected="selected"':''?>><?php echo $country['name']; ?></option>
<?php endforeach; ?>
</select>
<label class="control-labels ">City</label>
<div id="emiratewrap">
<select name="emirate" id="emirate">
<option value="">Select City</option>
</select>
AJAX
$(document).ready(function () {
getcities($('#country').val());
});
function getcities(obj){
console.log(obj);
var dataString = new Object();
dataString.emirate = '<?php echo $property->emirate ?>';
$.ajax({
type: "get",
dataType:"json",
url: "<?php echo site_url('listings/ajaxgetcitiesedit'); ?>/"+obj,
data: dataString,
success: function(e) { $('#emiratewrap').html(e.result);
$bb = "<?php echo $property->status; ?>";
if($bb=="Y") {$("#emiratewrap select").addClass("disabled"); }
}
});
}
Controller:
function ajaxgetcitiesedit($country=''){
$emirate = $this->input->get('emirate');
if(!$country) return false;
$cities = $this->listings_model->get_activepair_cities(array('country_id'=>$country),'*','name asc');
$html = '<select name="emirate" id="emirate" class="form-control select2 required" onchange="oemirate(this);">';
$html .= ($emirate <1)? '<option value="">Select Emirate</option>':'';
foreach($cities as $city):
$html .= '<option value="'.$city['id'].'" '.($city['id'] == $emirate ? 'selected="selected"' : '').'>'.$city['name'].'</option>';
endforeach;
$html .= '<option value="Other">Other</option> </select><input type="text" id="other_emirate" name="other_emirate" class="form-control" style="display: none;" />';
echo json_encode(array('result'=>$html));
}
Now currently I'm working on edit page where it should initially show what value the user had selected while adding the entry. As of now the functionality of the second select works fine as intended as it changes its options when the 1st select data is changed and also gives the correct value in database when update is pressed.
Now the only problem here I have is that initially when loading into the page, it doesn't show anything in the second select box even though there is a value for it in the database. I performed a console.log(obj); in getcities(obj) and initially it returned undefined and everytime I change country, it gives a value in my log.

how to change value of select options based on another select option selected?

I am not sure the title is explained perfectly.
I have 2 select tags and both select tags data are coming from the same table, in
The fist select tag - I am fetching data from the database which stores location name => This works perfectly and I have 3 locations name in the database.
<select name="location" class="form-label" id="location" required>
<option value="">Select Dojo Location</option>
<?php foreach ($location as $row): ?>
<option value="<?php echo $row->id; ?>"><?php echo $row->location; ?></option>
<?php endforeach; ?>
</select>
Image for first select tag
The second select tag - I am fetching prices from different columns of the same table but it shows every price from different locations.
<select name="month" class="form-label" id="month" required>
<option value="">Select Fees Period</option>
<?php foreach ($location as $row1): ?>
<option value="<?php echo $row1->admission_fee_1; ?>">Monthly</option>
<option value="<?php echo $row1->admission_fee_1; ?>">Quarterly</option>
<option value="<?php echo $row1->admission_fee_6; ?>">Half Yearly</option>
<option value="<?php echo $row1->admission_fee_12; ?>">Annually</option>
<?php endforeach; ?>
<?php endif; ?>
Image for second select tag
Image for table data
What I am trying to do is, when user select location in 1 select tag, so it only shows the prices of that selected location from database in second select tag.
This is what I am getting in the result
But I do not succeed yet, any solution is helpful or is there any other way to do this or am I doing it wrong.
Thanks in advance.
You have to use JavaScript and onChange method. It was resolved manytimes, e.g. how to change a selections options based on another select option selected?
You need to make some ajax call.
On Selection of first location tag; you can make jQuery Ajax call and get prices of that selected location only. In Ajax response you can receive HTML of second select tag and replace with current one.
Let me know if you need further explanation.
You need fetch the data dinamically.
Something like this
$( "#location" ).change(function() {
// this.value is your ID
$.post('/endpoint/fetch-details/' + this.value)
.done(function(data) {
// load data into another SELECT
})
.fail(function() {
alert( "error" );
})
});
On Codeigniter you could have a controller method (/endpoint/fetch-details/) that returns a JSON object.
Successfully Done...
Ajax function =>
$(document).ready(function () {
$('#location').on('change', function () {
var location_id = $(this).val();
if (location_id == '') {
$('#fees').prop('disabled', true);
} else {
$('#fees').prop('disabled', false);
$.ajax({
url: "<?php echo $base_url;?>welcome/getFeePeriod",
type: 'POST',
data: {location: location_id},
dataType: 'json',
success: function (data) {
//alert("Ok");
$('#fees').html(data);
},
error: function () {
alert("Error Accured...");
}
});
}
});
});
Controller function =>
public function getFeePeriod()
{
$location_id = $this->input->post('location');
$FeesPeriod = $this->admin_model->getFeePeriod($location_id);
if (count($FeesPeriod)>0) {
$fee_select_box = '';
$fee_select_box .= '<option id="">Select Fee Period</option>';
foreach ($FeesPeriod as $fees) {
$fee_select_box .= '<option id="' . $fees->admission_fee_1 . '">Monthly</option>+
<option id="' . $fees->admission_fee_3 . '">Quarterly</option>+
<option id="' . $fees->admission_fee_6 . '">Half Yearly</option>+
<option id="' . $fees->admission_fee_12 . '">Yearly</option>';
}
echo json_encode($fee_select_box);
}
}
model function =>
function getFeePeriod($location_id){
$query = $this->db->get_where('location', array('id'=>$location_id));
return $query->result();
}
Thanks everyone for their response...

PHP: Passing selected list value to another variable in the same page

I have a form, having two list boxes and based on the selected field from the first list, I have to fetch data from the database to create second list box.
I am trying to acheive this with post method, but unable to understand why mey second list is not populating with data...
PHP to fetch data for second list box
if (isset($_POST['val']))
{
$value = $_POST['val'];
$smt3 = $db->prepare('select floor from test where name_id =?');
$smt3->execute(array($value));
$HF_id = $smt3->fetchAll();
}
HTML to for the list boxes
<select class="Name" name="Profile_Name1" id="PC1">
<option value="A">AA</option>
<option value="B">BB</option>
<option value="c">CC</option>
<option value="d">DD</option>
</select>
<label>Home Floor </label>
<select name="Home_Floor" id="hfid"> <br />
<option value="">Home_Floor</option>
<?php foreach ($HF_id as $row){echo '<option value="' . $row['floor'] . '">' . $row ['floor'] . '</option>';}?>
</select>
Jquery
$('#PC1').on('click', function() {
$.post('user_info1.php', 'val=' + $(this).val(), function (response) {
$.ajax({
url: 'user_info1.php', //This is the current doc
type: "POST",
data: ({val: + $(this).val()}),
success: function(data){
}
});
You seem to expect the post function to trigger a loading of the page specified by the URL parameter.
Try something along the lines of this:
HTML
<select class="Name" name="Profile_Name1" id="PC1">
<option value="A">AA</option>
<option value="B">BB</option>
<option value="C">CC</option>
<option value="D">DD</option>
</select>
<label>Home Floor </label>
<select name="Home_Floor" id="hfid">
</select>
loaddata.php
if (isset($_POST['val']))
{
$value = $_POST['val'];
$smt3 = $db->prepare('select floor from test where name_id =?');
$smt3->execute(array($value));
$HF_id = $smt3->fetchAll();
$HF_array=array();
foreach ($HF_id as $row)
{
$HF_array[]=$row['floor'];
}
}
echo json_encode($HF_array);
javascript/jquery
jQuery('#PC1').on('click', function() {
jQuery.ajax({
url: 'loaddata.php',
type: "POST",
data: ({val: + $(this).val()}),
success: function(data){
//data should come as JSON string in the form of ['item1','item2','item3'] use JSON.parse to convert to object:
jQuery.each(JSON.parse(data), function(key, datavalue) {
jQuery('#hfid').append(
jQuery('<option>', { value : datavalue })
.text(datavalue)
);//end of append
});//end of each
}//end of success function
});//end of ajax datastruct and ajax call
});//end of on-click-function

Getting the value of textbox

I have a select option, to get the value from this, I used jquery (please see below code). After I display the selected value in the textbox, I'm now having problem on how to get the value of textbox to process a such code. Even simply echo of the value is not working. What's the problem with the code? Please help. Thanks.
Select option:
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
Jquery:
$('#shiptype').change(function () {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
}
});
Text Field:
<input type='text' id='strkey' name='keyname' />
Display the value:
$key = $_POST['keyname'];
echo $key;
Please try this code :
HTML file contains this below code. File name test.html.
Form to submit your data.
<form id="frm_post">
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
<input type="text" name="name" id="strkey">
<input id="btn_post" type="button" name="submit" value="Submit">
</form>
This is a div for your output.
<div>
<p id="output"></p>
</div>
This is jquery for ajax call function.
<script>
$(document).ready(function(){
$('#shiptype').change(function() {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
}
});
$("#btn_post").click(function(){
var parm = $("#frm_post").serializeArray();
$.ajax({
type: 'POST',
url: 'your.php',
data: parm,
success: function (data,status,xhr) {
console.info(data);
$( "#output" ).html(data);
},
error: function (error) {
console.info("Error post : "+error);
$( "#output" ).html(error);
}
});
});
});
</script>
And for PHP File to get the post value like this below. File name your.php.
<?php
// $key = $_POST['keyname'];
// echo $key;
print_r($_POST);
?>
Your post result will be show up in output id. Hope this help you out. :D

How multiselect post in array?

This my code. How this multiselect values with array to post modelseardh.php
<p>
<label>Country:</label>
<select multiple="multiple" name="country[]" class="qs_carlocation1 carlocations" onChange="jsFunction()" id="selectOpt">
<?php
$sql_se = mysql_query('select * from `country`');
while($se = mysql_fetch_assoc($sql_se)) {
?>
<option value = "<?php echo $se['id'];?>"><?php echo $se['country'];</option>
<?php
}
?>
</select>
</p> `
<p id="change_form">
<label>Mark:</label>
<select multiple="multiple"name="search_mark[]"class="qs_carlocation1 carlocations" >
<?php
$sql_search_mark = mysql_query('select * from `mark`');
while($smark = mysql_fetch_assoc($sql_search_mark)) {
?>
<option value="<?php echo $smark['id'];?>"><?php echo $smark['name'];?></option>
<?php
}
?>
<script>
function jsFunction(){
var select = document.getElementById("selectOpt").value;
$.post(
"modelsearch.php",
{
id: "" + select + ""
},
function(data)
{
$('#change_form').html(data);
}
);
}
</script>
</select>
</p>
<?PHP
//this modelsearch.php
include('../db.php');
$id = $_POST['id'];
?>
There's wrong with enclosing & misplaced tag in the following line that possibly make the rendering ouput fails:
<option value = "<?php echo $se['id'];?>"><?php echo $se['country'];"></option>
which is missing ?>"> right before the </option>, and you need to remove "> between ?> <?php
it should be :
<option value = "<?php echo $se['id'];?><?php echo $se['country'];?>"></option>
and you also don't ouput any values between <option> xxx </ouput>, so the value attribute is assigned in the <option> but nothing to be ouput. I meant that xxx to be output
and FYI , you dont need to multiple echo the values, just concatenate the values :
<option value = "<?php echo $se['id'] +""+ $se['country'];?>" ></option>
First of all, you don't need to keep the country name in Array change country[] to country only
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script language='javascript'>
function showselection()
var frm = document.testingform //this is the name of the form can be as your form name
var opt = frm.country //this is the multiselect option name
var numofoptions = opt.length
var selValue = new Array
var j = 0
for (i=0; i<numofoptions; i++)
{
if (opt[i].selected === true)
{
selValue[j] = opt[i].value
j++
}
}
var myvalues=document.getElementById('yourhiddenvaluename').value=selValue;
$.post( 'modelsearch.php',{ newva: myvalues }, function( data ) {
$('#change_form').html(data)
});
}
</script>
<select name='country' multiple onchange='showselection()'>
//Your values
</select>
<input type="text" id="yourhiddenvaluename" name="seletedvalued" />
In modelsearch.php:
print_r($_POST['newva']);

Categories