PHP get selected value of select form - javascript

I'm using Laravel and currently creating a form, where users can first choose a category, and then choose a relating subcategory.
A category has an id and a name, a subcategory has an id and a name, as well as a parent_id (so that's the id of the parent category).
Now I try the following:
The user can pick a category, after he did that, the second select appears and the user can choose the subcategory from the subcategories that belong to the parent category (and only those!).
Therefore, the view gets all categories and all subcategories from the controller.
Then, for the categories I did this:
<div class="form-group{{ $errors->has('category') ? ' has-error' : '' }}">
<label for="category" class="col-md-4 control-label">Kategorie</label>
<div class="col-md-6">
<select>
#foreach($categories as $category)
<option value="<?php echo $category['id'];?>">{{$category->name}}</option>
#endforeach
</select>
</div>
</div>
And for the subcategories I have the same, just with subcategories:
<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
<label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
<div class="col-md-6">
<select>
#foreach($subCategories as $subCategory)
<option value="<?php echo $subCategory['id'];?>">{{$subCategory->name}}</option>
#endforeach
</select>
</div>
</div>
Now the question is: What I need to do is (in the subcategory foreach) a #if and check for the value of the chosen option of the category select and then check if($subcategory->parent_id == $chosenOptionID), to say it in pseudo code. How can I do this? I don't want to send the form or something, before somebody didn't choose the subcategory as well.... Of course, I maybe could send an ajax request to the controller whenever a category is chosen, then check the value of the option in the controller and send back the id. But this would cause very much traffic and would propably not be the best solution, so I'd like to do this only, if I don't get a better way to do....
PS: The question is not about hiding the subcategories when no category is chosen, thats basic js, I know how to do that. I only want to know, if it is possible to read the value of the category select while form is not sent yet.
EDIT: I now tried the AJAX thing but there seems to be a little error...
What I changed:
<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
<label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
<div class="col-md-6">
<select class="form-control" id="subCategorySelect">
</select>
</div>
</div>
The select is now empty and has an ID. Then in the same file I have the following JS:
<script>
$().ready(function(){
$('#categorySelect').change(function(){
var selectedOption = $('#categorySelect').find(":selected").val();
$.ajax({
url: '/getSubCategories',
data: {'id': selectedOption},
type: 'GET',
success: function (data) {
$('#subCategorySelect').html(data);
}
});
});
});
</script>
/getSubcategoriesroute points to the following function in my controller:
public function returnSubCategories(Request $request){
$subCategories = Subcategory::where('parent_id', '=', $request->id);
foreach($subCategories as $subCategory){
echo "<option value='$subCategory->id'>$subCategory->name</option>";
}
}
But it doesn't work.. The ajax request is defintely sent on selecting an option, as well the correct id is sent. But somehow nothing is outputted... Any ideas why?

I finally got it working with AJAX. This is my initial subCategorySelect.
<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
<label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
<div class="col-md-6">
<select class="form-control" id="subCategorySelect">
</select>
</div>
</div>
The select is now empty and has an ID. Then in the same file I have the following JS:
<script>
$().ready(function(){
$('#categorySelect').change(function(){
var selectedOption = $('#categorySelect').find(":selected").val();
$.ajax({
url: '/getSubCategories',
data: {'id': selectedOption},
type: 'GET',
success: function (data) {
$('#subCategorySelect').html(data);
}
});
});
});
</script>
/getSubcategoriesroute points to the following function in my controller:
public function returnSubCategories(Request $request){
$subCategories = Subcategory::where('parent_id', '=', $request->id)->get();
foreach($subCategories as $subCategory){
echo "<option value='$subCategory->id'>$subCategory->name</option>";
}
}
And it works perfectly.

hope this will help you understand how it works with php anyway for one selected option:
<div class="form-group">
<label class="control-label" for="country">Country:<span>*</span></label>
<select name="country" type="text" class="form-control" id="country">
<option value="">--Country--</option>
<?php
include "../db/db.php"; //db-connection cause i want to load a country list
$sql = "SELECT id, country_name FROM apps_countries ORDER BY country_name ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //check if an entry is there
while($row = $result->fetch_assoc()) { //get the values from the db
//now this is the part you have to implement in your script
if(isset($_POST["country"]) && $row["id"] == $_POST["country"]) { //check if country isset so if the user selected something
$optionSelected = "selected='selected'";
} else{
$optionSelected = "";
}
//your foreache loop goes here / add the value that is selected here
/*#foreach($categories as $category)
<option value="<?php echo $category['id']; ?>">{{$category->name}}</option> // get the associative array with "" and change it to $category["id"]
#endforeach*/
/**for my attempt it was this
{the id like as your category[id]} {set the selected here inside the option tag}
↓ ↓ */
$countrySet = "<option value='" .$row["id"]. "' ".$optionSelected.">".$row["country_name"]."</option>";
echo $countrySet;
}
}
$conn->close();
?>
</select>
</div>

Related

How to keep jQuery auto populated dropdown result selected?

I have this dynamic dropdown which fetches result on selection of one select menu, but the challenge I am facing after it auto populates the results on the second dropdown on submit of form the value of second select disappears. How to make it not disappear even after submit?
Here is my HTML & PHP
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="job_category">Select Job Category</label>
<select name="job_category" id="category" class='form-control'>
<option value='' selected='selected' disabled='disabled'>Select Job Category</option>
<?php
$sql="select * from job_category ";
foreach ($db->query($sql) as $row) {
?>
<option value='<?php echo $row[cat_id]; ?>' <?php if($job_category == ''.$row[cat_id].'') echo 'selected="selected"'; ?>><?php echo $row[cat_name]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class='row form-group'>
<div class='col-md-12'>
<label class='sr-only' for='job_subcategory'>Select Job Industry</label>
<select name='job_subcategory' id='sub-category' class='form-control'>
<option value='' selected='selected' disabled='disabled'>Select Job Industry</option>
</select>
</div>
</div>
Here is my JQ
$(document).ready(function() {
$('#category').change(function(){
var cat_id=$('#category').val();
$('#sub-category').empty();
$.get('fetchCategories.php',{'cat_id':cat_id},function(return_data){
$.each(return_data.data, function(key,value){
$("#sub-category").append("<option value='" + value.subcat_id +"'>"+value.subcat_name+"</option>");
});
}, "json");
});
});
And my fetchCategories.php
#$cat_id=$_GET['cat_id'];
//$cat_id=2;
/// Preventing injection attack ////
if(!is_numeric($cat_id)){
echo "Data Error";
exit;
}
/// end of checking injection attack ////
require "includes/config.php";
$sql="select subcat_name,subcat_id from job_subcategory where cat_id='$cat_id'";
$row=$db->prepare($sql);
$row->execute();
$result=$row->fetchAll(PDO::FETCH_ASSOC);
$main = array('data'=>$result);
echo json_encode($main);
You can use localStorage to store the current value which is selected by user on change of select-box and then when your page gets reload just fetch the stored data from localStorage and then call your ajax to retrieve required data.
Your jquery code will somewhat look like below (Sorry for any syntax error) :
$(document).ready(function() {
//check if there is any value in localStorage
if (localStorage.getItem("save") != null) {
//get that value
var value = localStorage.getItem("save");
console.log(value);
//set value in selected box
$("#sub-category").val(value);
}
//onchange of subcategory
$('#sub-category').change(function() {
var values = $(this).val();
localStorage.clear(); //clear previous data
localStorage.setItem("save", values); //add data to storage
});
$('#category').change(function() {
var cat_id = $('#category').val();
$('#sub-category').empty();
$.get('fetchCategories.php', {
'cat_id': cat_id
}, function(return_data) {
$.each(return_data.data, function(key, value) {
$("#sub-category").append("<option value='" + value.subcat_id + "'>" + value.subcat_name + "</option>");
});
}, "json");
});
});

How to post select box and not the value of select box

I have a form, I use the value to generate a dropdown list using ajax. When I post this form to database the value enters into database, but I want the actual name to be entered.
<form action='' method='post'>
<select name="region">
<option disabled selected hidden>---Select---</option>
<?php
$region_sql = "SELECT * FROM `regions`";
$region_res = mysqli_query($con, $region_sql);
if(mysqli_num_rows($region_res) > 0){
while($region_row = mysqli_fetch_array($region_res)){
echo "<option value='".$region_row[id]."'>".$region_row[region]."</option>";
}
}
?>
</select>
<div class="form-group col-sm-4">
<div class="row">
<div class="col-sm-3">
<label for="city">City</label></div>
<div class="col-sm-7">
<select class="form-control" name="city" id="city" data-live-search="true">
<option>First choose a Region</option>
</select>
</div>
</div>
</div>
</form>
This array is the issue: echo "<option value='".$region_row[id]."'>".$region_row[region]."</option>
It ends up being: <option value="1">mid atlantic</option>
value being 1, 2, 3, 4, or 5 etc etc..
1 gets entered to the database, but I want mid atlantic to enter in the database.
Is there a way to do this?
thanks!
Update
I am using the Id to post it to getstate.php
ajax:
$(document).ready(function(){
$("#region").change(function()
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "getState.php",
data: dataString,
cache: false,
success: function(html)
{
$("#state").html(html);
}
});
});
});
getstate.php:
if($_POST['id']){
$region_id=$_POST['id'];
$sql= "select * from states where region_id='$region_id' ORDER BY state ASC";
$res= mysqli_query($con, $sql);
echo "<option>---Select--</option>";
if(mysqli_num_rows($res) > 0){
while($row = mysqli_fetch_array($res)){
echo "<option value='".$row['id']."'>".$row['state']."</option>";
}
}else{
die('there was an error running query [' . $con->error . ']');
}
}
The code works as is. I just want it to enter the name in the database and not the id number.

jquery about attributes ( load from loaded html )

I have a 2 select options. When I select the first one it posts to a link using javascript then return full options to the second one with data from a database.
I have an attributes in the second select called data-price. When I'm trying to use it, it shows nothing:
var x = $("#services").find(':selected').attr('data-price');
However when I'm trying with the first select attribute it works correctly. Anyone know how to fix ? Thanks
<script type="text/javascript">
$(document).ready(function(){
var category = document.getElementById("category").value;
$.ajax({
type:'POST',
url:'<?=base_url();?>dashboard/ajaxData',
data:'main_category='+category,
success:function(html){
$('#services').html(html);
}
});
$('#category').on('change',function(){
var category = $(this).val();
if(category){
$.ajax({
type:'POST',
url:'<?=base_url();?>dashboard/ajaxData',
data:'main_category='+category,
success:function(html){
$('#services').html(html);
}
});
}else{
$('#services').html('<option value="">Select category first</option>');
}
});
});
var x = $("#services").find(':selected').attr('data-price');
document.getElementById("demo").innerHTML = x;
</script>
<div class="form-group">
<label>Category</label>
<select name="category" id="category" class="form-control">
<?php foreach($categories->result() as $cat): ?>
<option data-price="55" value="<?=$cat->id;?>">- <?=$cat->title;?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Service</label>
<select name="service" id="services" class="form-control">
<option data-price=""></option>
</select>
</div>
<div id="demo"></div>
To find the selected one you do:
$("#services option:selected")
then you can get whatever you want from that option.
For a data attribute it can be:
$("#services option:selected").data('price');
or alternatively
$("#services option:selected").attr('data-price');
This answer is based on the assumption that your select as an id attribute of services, if it is not all the above code will fail
Based on the updated code you posted you probably are looking to update the selected value when the user changes the selection.
I'd do it binding the change event like this:
$("#services option:selected").change(function(){
var price = $(this).attr('data-price');
$('#demo').html(price);
});

Pass URL parameters to Select options with JavaScript and Php

I am kinda new in JavaScript and need some help.
I have a search form in my navigation menu.
Here is my code php+html for the form.
<form action="search.php" name="form-name" method="GET" enctype="multipart/form-data">
<div class="row">
<div class="col-lg-2 col-md-12 col-sm-12 search">
<label>Destination</label>
<select required name="country" id="destination" onChange="getCity(this.value);">
<option value="">Any destination</option>
<?php $query = "SELECT * FROM countries";
$select_region_query = query($con, $query);
while ($row = fetch($select_region_query)) {
$region_id = $row['country_id'];
$region_name = $row['country_name'];
echo "<option value='".str_replace("&", "and",$full_region)."'>$full_region</option>";
}
?>
</select>
</div>
<div class="col-lg-2 col-md-12 col-sm-12 search ">
<label>City</label>
<select name="city" id="city" onChange="get_dropdown_ajax(this.value);">
<option value="">Any Cruise Line</option>
<?php $query = "SELECT * FROM cities";
$select_city_query = query($con, $query);
while ($row = fetch($select_city_query)) {
$city_id = $row['city_id'];
$city_name = $row['city_name'];
$city_name_value = str_replace("&"," and ",$row['city_name']);
echo "<option value='$city_name_value'>$city_name</option>";
}
?>
</select>
</div>
<div class="input-group col-lg-4 col-md-12 col-sm-12 search">
<label>Dates</label>
<select name="date_1" id="date_1">
<option value="">Any Day</option>
<?php
for($i=0;$i<31;$i++){
$i = str_pad($i,2,"0",STR_PAD_LEFT);
echo "<option value='$i'>$i</option>";
}
?>
</select>
<select name="date" id="date">
<option value="">Any Month</option>
<?php
for ($i = 0; $i <= 36; $i++) {
$time = strtotime(sprintf('+%d months', $i));
$value = date('Y-m', $time);
$label = date('F-Y', $time);
$label = str_replace("-", " ", $label);
echo "<option value='$label'>$label</option>";
}
?>
</select>
<input type="hidden" id="datepicker">
</div>
<div>
<button type="submit" name="search" class="search_button_nav btn btn-info">
<span class="glyphicon glyphicon-search"></span></button>
</div>
</div>
</form>
What I need to achieve is when the user doing a search to get these URL parameters and use these to change my select options based on their choices.
e.g If they search for country United Kingdom on search page my dropdown on countries to display United Kingdom instead of Any Destination.
I tried to do that with php $_GET but I am not sure is a good idea, because my country list is really big and I can create for every country if(issets($_GET)=='United Kingdom)' etc..
Is that something can complete with javascript without have to check the query of url like i tried with php?
I seach for solution and I find on other posts that (window.location); probably can help me.
I tried to console.log(window.location) and I can see the parameters, but how can I split them properly and use them with php?
Any feedback would be helpful.
P.S My url is looking like this one : nameofmysite/search.php?country=+United+Kingdom&chk=1&city_name=%25date_1=05&date=July+2018
I am not sure whether I understand your problem If you just want to set the dopdown-item to the city the user is searching for, using $_GET is no bad idea. You just have to check whether the parameter is given, then you can use it in PHP.
if(isset($_GET['search'])) {
echo "<option value='".$_GET['search']."'>".$_GET['search']."</option>";
} else {
echo "<option value=''>Any destination</option>";
}
I think you are trying to mix the use of the parameter.
Once the request is sent, the server will process that request and interpret the PHP page in the server before send it to the client (the browser). If you need to check a parameter then you can get it with the global variable $_GET and do whatever you want and build your page conveniently.
Get request parameters from URL in PHP GET URL parameter in PHP
Once the page is built it is sent to the client wich interpret it and your browser renders it. Then you can get the URL with window.location and parse it conveniently with split method or Regular expressions to get what you want from there.
Get request parameters from URL in Javascript How to get URL parameters with Javascript?
But the page is already rendered and what you can do then is manipulate the DOM of the page.

Ajax Php dependent dropdown select - How to post name of city instead id into database (submit from data)?

Few days I try to solve problem but no luck.
Problem is next:
Web form with dependent dropdown select box where user can select his
city, zip and street and that work but.
When I submit form in my database no city_name (text) - only city_id (number/value).
So, question is - How to post city_name in database? User is from Rome and I Rome (text) is submited not city_id (number).
Select input:
<div class="form-group">
<label class="col-md-4 control-label" for="grad">City:*</label>
<div class="col-md-4">
<select type="text" name="city_name" id="city_name" class="form-control input-sm">
<option value=""></option>
<option value="999">---Enter city yourself---</option>
<?php $sql_query="SELECT * FROM city_table order by city_id asc";
$result=mysqli_query($dbconfig,$sql_query);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
?>
<option value="<?php echo $row['city_id'].'_'.$row['city_name'];?>"><?php echo $row['city_name'];?></option>
<?php }?>
</select>
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="post_no">ZIP code:*</label>
<div class="col-md-4">
<select name="zip_name" id="zip_name" class="form-control input-sm" onchange="recalculate_price();">
</select>
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="address">Street:*</label>
<div class="col-md-4">
<select name="street_name" id="street_name" class="form-control input-sm" onchange="recalculate_price();">
</select>
</div>
</div>
get_zip_php
<?php
include('db_config.php');
if($_POST['id'])
{
$id=$_POST['id'];
$sql_query="SELECT * FROM zip_table where city_id='$id' order by zip_name asc";
$result=mysqli_query($dbconfig,$sql_query);
?>
<option selected="selected">Select ZIP code :</option><?php
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
?>
<option value="<?php echo $row['zip_id']; ?>-<?php echo $row['limousine']; ?>-<?php echo $row['kombi']; ?>-<?php echo $row['mini_van']; ?>"><?php echo $row['zip_name']; ?></option>
<?php
}
}
?>
get_street_php
<?php
include('db_config.php');
if($_POST['id'])
{
$id=$_POST['id'];
$sql_query="SELECT * FROM street_table where zip_id='$id' order by street_name asc";
$result=mysqli_query($dbconfig,$sql_query);
?>
<option selected="selected">Select street please :</option><?php
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
?>
<option value="<?php echo $row['street_id']; ?>"><?php echo $row['street_name']; ?></option>
<?php
}
}
?>
Ajax:
<script>
$(document).ready(function()
{
$("#city_name").change(function()
{
var id=$(this).val();
var data = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_zip.php",
data: data,
cache: false,
success: function(html)
{
$("#zip_name").html(html);
recalculate_price();
}
});
});
$("#zip_name").change(function()
{
var id=$(this).val();
var data = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_street.php",
data: data,
cache: false,
success: function(html)
{
$("#street_name").html(html);
recalculate_price();
}
});
});
});
</script>
If I make some changes on "select city part" (Im beginner and really Im lost in all this) I can`t pass zip.
So, please tell me where to make all changes to pass all that things and post city_name, zip (name...I make it as "xxxx - city") and street name. Please help me, I googled and read here about problems few days and can`t continue work on my project until I fix this. Thanks in advance.
Use bellow select tag. It may useful for you
<select type="text" name="city_name" id="city_name" class="form-control input-sm">
<option value=""></option>
<option value="999">---Enter city yourself---</option>
<?php
$sql_query="SELECT * FROM city_table order by city_id asc";
$result=mysqli_query($dbconfig,$sql_query);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<option value='".$row['city_id']."'>".$row['city_name']."</option>";
}
?>
</select>
Concatenate the id with value like this using delimiter like this
<option value="<?php echo $row['city_id'].'_'.$row['city_name'];?>"><?php echo $row['city_name'];?></option>
In php use explode()
The explode() function breaks a string into an array.
$ss = explode('_','6_Rome');
print_r($ss);
echo $ss[0]; //6 pass the value into query
In jquery use split()
Split a string into an array of substrings:
use split()
$vv = variable_name.split("_");
fetch city name from database on the basis of city id in your POST array before INSERT Query.
SELECT `city_name` FROM `city_table` WHERE `city_id`='".$_POST['city_name']."'
then use that city name in your insert query.

Categories

Resources