Insert from combo box using php - javascript

I am populating a combo box from database, the problem is when I select an item from the combo box and try to save to another table in the database it picks the record ID column instead of the item itself.
this is the how am populating the combo box.
<label>State</label>
<select name="state" class="state" onChange="display(this.value)" width="142" style="width: 142px">
<option value="" selected="selected">-- Select State --</option>
<?php
$query="select * from tbl_state";
$query_result=mysql_query($query)or mysql_error();
while($row=mysql_fetch_array($query_result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['state_name']; ?></option>
<?php
}
?>
</select>
<div id="show_city" style="position: relative" height:5px;>
<label>LGA</label>
<select name="city" class="lga" width="142" style="width: 142px">
<option value="" selected="selected">-- Select LGA --</option>
</select>
</div>
</p>
Database connection
$state = $_POST['state'];
$city = $_POST['city'];
$sql="INSERT INTO members (state, city)
VALUES ('$state', '$city')";
NB. am using javascript to populate the combo box.

When you submit a form, only the field name along with its value will be sent. In your case, when the user select the state and press submit, the row id will be sent as you specify the row id at the option value tag.
Either you can use <option value="<?= $row['state_name'] ?>"> ... </option>" and then get the state name ini php directly:
$state = $_POST['state'];
or leave the populating code as is now and get the state name by querying database using the record id.
$state_id = intval($_POST['state']);
$city_id = intval($_POST['city']);
$sql = "SELECT `state_name` FROM tbl_state WHERE id=$state_id";
$query_result = mysql_query($sql) or mysql_error();
$state = mysql_result($query_result, 0);
echo $state;
getcity.php
<?php
$con=mysql_connect('localhost','root','') or die('Mysql not connected');
mysql_select_db('thriftdb',$con) or die('DataBase not connected');
$state_id=$_REQUEST['state_id'];
$query="select * from lga where state_id='$state_id'";
?>
<label>LGA</label>
<select name="city" width="142" style="width: 142px">
<option value="" selected="selected">-- Select LGA --</option>
<?php
$query_result=mysql_query($query)or mysql_error();
while($row=mysql_fetch_array($query_result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['lga_name']; ?></option>
<?php
}
?>
</select>
database structure is as follows
'lga' table has...
lga_id --- state_id --- lga_name
'state' table has
state_id --- state_name

When a form sends the selected item of a combo, it sends the value of the option selected, not the text. If you want to send the text, add a hidden input for every combo, then in the onclick event of the combos, call a function that populates the text to the hidden input.
selectState = function() {
$('#hiddenInputField').val($("select[name='state'] option:selected").text());
}
Then in the server side you must get the value of the input hidden field instead of the select field.

Related

How to restrict user to submit form if he doesnot select value from select Box-PHP

I am working on a project where admin have rights to add new users.
In ADD NEW USER form i have a select BOX of Designation which is populated from database . i want to know if user not select any designation from select options it will give error please select designation or some thing like this.
Here is my code:
<select class="form-control" name="designation" id="designation" style="color: black;" required>
<option value="<?php echo $row['designation_id']; ?>">Please Select designation</option>
<?php
$sel_cus = "select designation_name ,designation_id from designation ";
$res_cus = mysqli_query($connection, $sel_cus);
while ($row = mysqli_fetch_array($res_cus)) { ?>
<option value="<?php echo $row['designation_id ']; ?>"><?php echo $row['designation_name']; ?></option>
<?php
}
?>
</select>
If selected index of select box is 0 which is [Please Select designation] it will give error please select designation from list.
Need kind guidance.
You are accessing $row variable before it even exist in the following statement,
<option value="<?php echo $row['designation_id']; ?>">Please Select designation</option>
please replace this statement with following,
<option value="">Please Select designation</option>
value should be blank for the first option of select to work with required attribute.
Refer to this specification
And if you dont want the error to appear just remove the required attribute from the select element.
You can use this approach.
<form action="" method="post" onsubmit="return validateForm()">
<select class="form-control" name="designation" id="designation" style="color: black;" required>
<option value="0">Please Select designation</option>
<option value="1">designation 1</option>
<option value="2">designation 2</option>
</select>
<input type="submit" value="Submit">
</form>
<script>
function validateForm(){
var e = document.getElementById('designation');
var selectedDesig = e.options[e.selectedIndex].value;
if(selectedDesig == 0){
alert('Please Select designation');
return false;
}
return true;
}
</script>

Send a JavaScript variable to PHP without POST

I have a HTML modal containing a form with a select tag and an input text.
Select options are extracted from a database like this.
<select id="select_1" name="select_1">
<?php
A code that access to DB
$sql = $bdd->query('SELECT * FROM my_table;');
while(#$fetch = $sql->fetch(PDO::FETCH_ASSOC)){
$id = $fetch['id'];
$name= $fetch['name'];
?>
<option id="<?php echo $id ; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<input type="text" id="input_1">
What I'm trying to do is when I choose an option from the select tag I want to output a field from a database relative to that select option in an input text.
For example let's pretend that my_table is defined this way and contains these:
| id | name | price |
+--------------+----------------+-----------------+
| 1 | A | 500 |
| 2 | B | 1000 |
My select tag will then contains the two options A & B:
<Option 1> A
<Option 2> B
When I select Option 1 (A) I want to output it's price in the input text so it will contain 500.
When I select Option 2 (B) 1000 will be output in the input text.
How Can I do that without submiting the form with POST and without closing the MODAL?
This is what I would do
<select id="select_1" name="select_1">
<?php
$sql = $bdd->query('SELECT * FROM my_table;');
while($fetch = $sql->fetch(PDO::FETCH_ASSOC)){ ?>
<option id="opt-<?php echo $fetch['id']; ?>" data-price="<?php echo $fetch['price']; ?>" ><?php echo $fetch['name']; ?></option>
<?php } ?>
</select>
<input type="text" id="input_1">
Then you can use (jQuery)
$('#select_1').on('change', function(){
$('#input_1').val($(this).find('option:selected').data('price'));
});
There is actually no need for AJAX, because the price comes from the same table. You can simply store it as a data attribute and then access it when the select changes.
But, remember it's an attribute of the option not the select. So you need to get the option that is selected. Which we can do with the sudo-selector :selected
$('#select_1').on('change', function(){
$('#input_1').val($(this).find('option:selected').data('price'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select_1" name="select_1">
<option id="opt-0" data-price="" >Pick an Option</option>
<option id="opt-1" data-price="500" >A</option>
<option id="opt-2" data-price="1000" >B</option>
</select>
<input type="text" id="input_1">
P.S. You are not really supposed to start an id with a number. So I added opt- to it.
Also you could just do this (use the value attribute):
<select id="select_1" name="select_1">
<?php
$sql = $bdd->query('SELECT * FROM my_table;');
while($fetch = $sql->fetch(PDO::FETCH_ASSOC)){ ?>
<option id="opt-<?php echo $fetch['id']; ?>" value="<?php echo $fetch['price']; ?>" ><?php echo $fetch['name']; ?></option>
<?php } ?>
</select>
I don't really see the need for the text input. Because when you submit this the value of select_1 in the Post or Get part of the submission will be the value of the select not the text of it.
But with out more about what you are doing, who can say.
You can do this using javascript or Jquery with and AJAX request.
Example using Jquery:
$(document).on('change','#select_1',function({
var value = $(this).value;
//DO your ajax request here and send the value inside the data
})
Because you have the values already loaded, passed into the select options values, using GlobalEventHandlers and an arrow function.
select_1.onchange = (()=> {
input_1.value = select_1.value
})
<select id="select_1">
<option value="1" selected> A </option>
<option value="2"> B </option>
</select>
<input type="text" id="input_1" value="1">

How to pass value into another page php using ajax

I am trying to pass a value of a select option input using Ajax into another page PHP and get the database and fetch data into select option. However, my problem is there is nothing to show in second select option.
I have the select option called Country which contains Country 1, Country 2, Country 3, Country 4 with cid 1,2,3,4.
what I wanted is past Country ID (cid) into getdata.php and query the database of City which contains City a, city b, city c, etc. and fetch city's data into select option using Ajax.
I need to make city select option dynamically change when I select the country.
here is my database structure :
Country.db
City.db
Here is my script :
dropdown.php
<?php
require_once "connection.php";
?>
<html>
<head>
<title>Dropdown ajax</title>
</head>
<body>
<div class="country" >
<label>Country</label>
<select name="country" onchange="getId(this.value);">
<option value=""> -- Select Country -- </option>
<!-- populate value using php -->
<?php
$query = "SELECT * FROM country";
$result = mysqli_query($con,$query);
//loop
foreach ($result as $country) {
?>
<option value="<?php echo $country["cid"]; ?>"> <?php echo $country["country"]; ?> </option>
<?php
}
?>
</select>
</div>
<div class="city">
<label>City</label>
<select name="city" id="cityList">
<option value=""></option>
</select>
</div>
<script src="jquery-3.2.1.min"></script>
<script type="text/javascript">
function getId(val){
// ajax function
$.ajax({
type:"POST",
url:"getdata.php",
data:"cid="+val,
success:function(data){
$(#cityList).html(data);
}
});
}
</script>
</body>
</html>
from the dropdown, I am trying to past cid into getdata.php using ajax and fetch the database into select option inside drop-down.php
getdata.php
<?php
require_once "connection.php";
if(!empty($_POST["cid"])){
$cid = $_POST["cid"];
$query = "SELECT * FROM city WHERE cid = $cid";
$result = mysqli_query($con,$query);
foreach ($result as $city) {
?>
<option value="<?php echo $city["cityId"];?>"><?php echo $city["city"];?></option>
<?php
}
}
?>
here is my connection.php
<?php
$con = mysqli_connect("localhost","root","admin","dropdowndb");
//check connection
if(mysqli_connect_errno()){
echo "Failed to connect :".mysqli_connect_errno();
}
?>
the result is like this :
so how to fix this problem?
The selector inside the ajax success handler must be a string, not identifier:
success:function(data){
$('#cityList').html(data);
}

Populate Dropdown based on another Dropdown Using Ajax, jQuery and Codeigniter on Update

I have created a dropdown that populates another dropdown.
I have created a modal for update in my application and I want the selected value of the dropdown to be the name taken from the database. It shows the name, but the problem is it doesnt show the other names which should be included.
(Note that the names show up depending on the first dropdown)
Here is my Model
function get_agents($campaign_id)
{
$campaign_id1 = mysqli_real_escape_string($this->db->conn_id,trim($campaign_id));
$query = $this->db->query("SELECT tbl_employee.emp_id, CONCAT(tbl_applicant.fname, ' ', tbl_applicant.lname) AS fullname FROM tbl_applicant INNER JOIN tbl_employee ON tbl_employee.apid=tbl_applicant.apid INNER JOIN tbl_account ON tbl_employee.acc_id=tbl_account.acc_id WHERE tbl_account.acc_id='".$campaign_id1."' ORDER BY tbl_applicant.fname ASC");
return $query->result();
}
Here is my Controller
public function getAgents()
{
$campaign_id = $this->input->post('campaign_id');
$data = $this->KudosModel->get_agents($campaign_id);
echo "<option value=''>-- Select Ambassador Name --</option>";
foreach($data as $a)
{
echo "<option value='".$a->emp_id."'>".$a->fullname."</option>";
}
}
Here is my View
<div class="form-group" style="height: auto; overflow: auto;">
<label class="col-sm-3 control-label float-left">Ambassador Name</label>
<div class="col-sm-9">
<select class="form-control" id="agentNames<?php echo $val->kudos_id; ?>" required="true" data-trigger="change" value="<?php echo $val->ambassador; ?>">
<option selected="" value="">-- Select Ambassador Name --</option>
<option selected="selected" value=""><?php echo $val->ambassador;?></option>
<?php
foreach($name2 as $row)
{
if($val->campaign==$row->acc_name)
echo '<'; if($val->ambassador==$row->fullname){
echo 'selected=selected';
}echo'option value="'.$row->emp_id.'">'.$row->fullname.'</option>';
}
?>
</select>
</div>
Here is my JQuery
$('#addCampaign<?php echo $val->kudos_id; ?>').on('change', function(){
$.ajax({
type : 'POST',
data : 'campaign_id='+ $('#addCampaign<?php echo $val->kudos_id; ?>').val(),
url : "<?php echo base_url(); ?>index.php/Kudos/getAgents/",
success : function(data){
//data returns your name, iterate through it and add the name to another select
$('#agentNames<?php echo $val->kudos_id; ?>').html(data);
}
});
});

City Area onchange in magento2

I am using magento 2.1.0. I created two dropdown on customer registration form ,where the data is fetching from database.
There are two databases :
city database which contain city_id and city column.
send is area table which contain area_id, city_id and area column.
on frontend data is sucessfully fetch, and even onchange is also working on city.
City dropdown:
<select name="city" onchange="getArea()" id="city">
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$model = $objectManager->create('/city')->serviceCity();
foreach ($model as $d)
{ ?>
<option id="<?php echo $d['city_id']; ?>" value="<?php echo $d['city_id']; ?>"><?php echo $d['city']; ?></option>
<?php } ?>
</select>
Area dropdown:
<div class="field area required">
<label for="area" class="label"><span><?php /* #escapeNotVerified */
echo __('Area') ?></span></label>
<select name="area" id="area">
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$model = $objectManager->create('\Area')->serviceArea();
foreach ($model as $a)
{ ?>
<option value="<?php echo $a['area']; ?>"><?php echo $a['area']; ?></option>
<?php } ?>
</select>
</div>
Onchange script:
<script>
function getArea(){
alert(document.getElementById('city').value);
}
</script>
Now my question is, what should I do, when I change the city, in second dropdown related area will display only?
Thanks in advance

Categories

Resources