I am using editable select to show drop down list.Depend on search if values is not present in table which initially generates dropdown then I check if values are present in other table and if yes then I want to reload drop down with new values.
Select in view is
<select tabindex="2" id="port_of_loading" name="port_of_loading" onkeyup="port_search()">
<option value=""></option>
<?php if(!empty($port_list))
{
foreach($port_list as $d)
{
?>
<option value="<?php echo $d->port_id; ?>"><?php echo $d->port_name; ?></option>
<?php } } ?>
</select>
and ajax is
var search_val = $("#port_of_loading").val();
$.ajax({
type:'POST',
cache:false,
async:false,
data: { 'search_val' : search_val },
url: 'URL',
success: function(data)
{
$("#port_of_loading").html(data);
}
});
I am refreshing it from controller.
consloe.log(data) output is
<select tabindex="2" id="port_of_loading" name="port_of_loading" onkeyup="port_search()">
<option value=""></option>
<option value="26">value1</option>
<option value="9">value2</option>
</select>
Related
I have some locations that are stored in my database separated by a comma and I have a dropdown that gets that information. The user selects a location to populate another drop down based on this chosen location.
Here is my php code:
<label for="select-service">
<strong>Enter a Location:</strong>
</label>
<select class="form-control" id="select-location" class="col-xs-12 col-sm-4 form-control" required>
<option value="">Select Location</option>
<?php
foreach($appointment_locations as $location) {
?>
<option value="<?php echo $location->notes ?>"><?php echo $location->notes ?></option>
<?php
}
?>
</select>
Here is my javascript code:
$(document).ready(function() {
FrontendBook.initialize(true, GlobalVariables.manageMode);
GeneralFunctions.enableLanguageSelection($('#select-language'));
$('#select-provider').html('');
$('#select-location').change(function() {
$('#select-provider').html('');
var selected_location = $(this).val();
$.ajax({
url: '<?php echo site_url('appointments/getProviderByLocation'); ?>',
type: 'POST',
data: {
csrfToken: GlobalVariables.csrfToken,
'selected_location': selected_location,
},
dataType: 'json',
success: function(data) {
var options = '';
$.each(data, function(key,val) {
console.log(val.id);
options += '<option value="'+val.id+'">'+val.first_name+" " +val.last_name +'</option>'
});
$('#select-provider').html(options);
}
});
});
and here is a screenshot of the location how it is currently:
So what i want to achieve is to have Randburg as one option, Greenside as another option and Rosebank as another option.
You have different type string in your array so for this particular problem in your loop you should explode your string like this and another loop to print separated string
<select class="form-control" id="select-location" class="col-xs-12 col-sm-4 form-control" required>
<option value="">Select Location</option>
<?php
foreach($appointment_locations as $location) {
$LocationsArray = explode(",", $location->notes);
foreach($LocationsArray as $singleLocation):
?>
<option value="<?=$singleLocation ?>"><?=$singleLocation ?></option>
<? endforeach;
};?>
here is the code.
<form method="POST" onChange="getHouseModel()">
<select name="house_model" id="house_model">
<option value="">------</option>
<option value="<?php echo $model1;?>">Model 1</option>
<option value="<?php echo $model2;?>">Model 2</option>
<option value="<?php echo $model3;?>">Model 3</option>
</select>
</form>
<script type='text/javascript'>
function getHouseModel(){
var model=$('#house_model').val();
alert(model);
}
</script>
Now i want to show the value of model variable in php.how can i do this?
You can use for example jQuery and a ajax call like:
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<form method="POST" onChange="getHouseModel()">
<select name="house_model" id="house_model">
<option value="">------</option>
<option value="<?php echo $model1;?>">Model 1</option>
<option value="<?php echo $model2;?>">Model 2</option>
<option value="<?php echo $model3;?>">Model 3</option>
</select>
</form>
<script>
$('#house_model').on('change', function() {
$.ajax({
url: 'test.php',
data: { house_model: $('#house_model').val() },
cache: false,
success: function(data) {
console.log(data)
}
});
});
</script>
test.php
<?php
var_dump($_REQUEST);
?>
First we bind a chnage event to the selction field and in this we do a ajax call to the PHP file (test.php) with the value of the selection.
If you need only the selection you can remove the form around it is not needed for the ajax call ;)
I have a form that gets submitted via ajax, inside that form there are two selects. these two selects get data from mysql using php.
I want is to show the second select only when the first select has been chosen, I've tried onchange and onsubmit but didn't get it to work. ajax script keeps preventing that! i even tried passing the value of the first select vie js to php, didn't work too.
<select class="form-control" name="sel1" onchange="recMarque();" required>
<option value="" hidden selected>Choose</option>
<?php
$r=$conn->query(sprintf("select * from stock")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel1))?($d[0]==$sel1)?'selected':null:null) .'>'.$d[0].'</option>';
}
?>
</select>
<script language="Javascript">
function recMarque(){
var p1 = $("select[name=sel1]").val();
alert(p1);
return p1;
}
</script>
<?php
$s1= "<script>document.writeln(recMarque());</script>";
echo $s1;
?>
<select class="form-control" name="sel2" required>
<option value="" hidden selected>Choose</option>
<?php
if(!empty($s1)){
$r=$conn->query(sprintf("select * from table where x='$s1'")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel2))?($d[0]==$sel2)?'selected':null:null) .'>'.$d[0].'</option>';
}
}
?>
</select>
Static html:
<select class="form-control" name="sel1" onchange="recMarque();" required>
<option value="" hidden selected>Choose</option>
<option value="AAA">AAA</option>
<option value="BBB">BBB</option>
</select>
<script language="Javascript">
function recMarque(){
var p1 = $("select[name=sel1]").val();
alert(p1);
return p1;
}
</script>
<script>document.writeln(recMarque());</script>
<select class="form-control" name="sel2" required>
<option value="" hidden selected>Choose</option>
</select>
I appreciate your help
Why are you using inline javascript while you are already loading the huge file of jQuery? Use jQuery change event and wrapp your hole code inside a jQuery DOM ready event. Additionnaly why are you mixing PHP with markup and javascript, this goes in contradition of AJAX purposes and of your goal descrption. You want to show the second select after selection from first select and the content depends on selected value (which require server side fetching) then send an XMLHTTPRequest to a separate (small) file and get the response.
$('select[name=sel1]').change(function(e) {
e.preventDefault();
var value = $('select[name=sel1] option:selected').val();
var text = $('select[name=sel1]',this).text();
var urlForSelect2 = $('select').attr('data-url');
// make an AJAX call and send value, text, and all your needed variable alongside
$.ajax({
type: "GET",
url: urlForSelect2,
dataType: 'html',
data: ({value: value, text: text}),
success: function(data){
$('select[name=sel1]').append(data);
});
return false;
});
And seperate the the php responsible for creating into another file with another url (urlForSelect2 in this case):
<option value="" hidden selected>Choose</option>
<?php
// Get the values sent along AJAX request using PHP $_GET, let's say $s1
if(!empty($s1)){
$r=$conn->query(sprintf("select * from table where x='$s1'")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel2))?($d[0]==$sel2)?'selected':null:null) .'>'.$d[0].'</option>';
}
}
?>
And the markup is becoming smaller and readable like:
<select class="form-control" name="sel1" data-url="recMarque();" required>
<option value="" hidden selected>Choose</option>
<?php
$r=$conn->query(sprintf("select * from stock")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel1))?($d[0]==$sel1)?'selected':null:null) .'>'.$d[0].'</option>';
}
?>
</select>
<select class="form-control" name="sel2" required>
<option value="" hidden selected>Choose</option>
</select>
Here is my solution
In the first select i've put onchange="selChange", the function is as follows:
<script type="text/javascript">
function selChange(){
var val = $("#sel1").serialize();
$.ajax({
type: "POST",
url: "select.php",
data: val,
success: function(data) {
$('#sel2').html(data);
}
});
return false;
}
</script>
I have 3 selectboxes the value of each selectbox gets populated based on the selection of the selectbox before it:
selectbox1 =>populates => selectBox2 => populates selectBox 3:
Now when user clicks submit I want to use the values from the selectboxes to query my database
My Problem
When I click submit:
The Whole Form Gets Duplicated (see image below)
So in short the variables are being passed correctly to my php code but the form duplicates on submit...
Code for sending form data
I believe the problem is somewhere in this code
<script type="text/javascript">
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {$('#resultForm').append(data); }
});
}
});
</script>
HTML
<form method="post" id="resultForm" name="resultForm">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
include('connect.php');
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
You're appending the result.
If you don't want to duplicate then replace the new content with old one.
Just change this
success: function(data) {$('#resultForm').append(data); }
to
success: function(data) {$('#resultForm').replaceWith(data); }
or even
success: function(data) {$('#resultForm').html(data); }
See more details about replacewith here
I have this simple dropdown menu in my codeigniter form. When clicking dzongkhag(district) it should display the list of geogs(towns), but, instead it do not do so. The drop down menu that I have is not the best one but that is what I could come up with after trying (for many weeks) many times unsuccessfully. I will be grateful if someone could help me out/solve/advice on this.
Here are the snippets.
view.php
<label >Dzongkhag: </label>
<select id="user_dzongkhag" name="dzongkhag" >
<option>Select Dzongkhag</option>
<option value="Bumthang">Bumtang</option>
<option value="Chhukha">Chhukha</option>
<option value="Dagana">Dagana</option>
<option value="Gasa">Gasa</option>
<option value="Haa">Haa</option>
<option value="Lhuentse">Lhuntse</option>
<option value="Monggar">Monggar</option>
<option value="Paro">Paro</option>
<option value="Pema Gatshel">Pema Gatshel</option>
<option value="Punakha">Punakha</option>
<option value="Samdrup Jongkhar">Samdrup Jongkhar</option>
<option value="Samtse">Samtse</option>
<option value="Sarpang">Sarpang</option>
<option value="Thimphu">Thimphu</option>
<option value="Trashigang">Trashigang</option>
<option value="Trashi Yangtse">Trashi Yangtse</option>
<option value="Trongsa">Trongsa</option>
<option value="Tsirang">Tsirang</option>
<option value="Wangdue Phodrang">Wangdue Phodrang</option>
<option value="Zhemgang">Zhemgang</option>
</select>
<label >Geog:</label>
<select id="user_geog" name="geog" >
<option> select geog</option>
</select>
javascript (which I implement it in the view.php instead of js folder)
$(document).ready(function(){
$('#user_dzongkhag').change(function(){
$('#user_geog').html('<option> Fetching...</option>');
var user_dzongkhag =$('#user_dzongkhag').val();
//alert(new_div);
$.ajax({
type:"post",
data:"user_dzongkhag="+user_dzongkhag,
url:"<?php echo site_url('ajax/select_auth_geog/'); ?>",
cache:false,
success:function(resp){
//alert(resp);
$('#user_geog').html(resp);
}
});
});
});
controller.php
public function select_auth_geog(){
$user_dzongkhag= $this->input->post('user_dzongkhag');
$returnGeog=$this->ajax_model->select_auth_geog($user_dzongkhag);
foreach ($returnGeog as $key) {
echo '<option value="'.$key['name'].'">'.$key['name'].' </option>';
}
}
model.php
public function select_auth_geog($user_dzongkhag){
if($user_dzongkhag=='Bumtang'){
$user_dzongkhag=1;
}elseif($user_dzongkhag=='Chhukha'){
$user_dzongkhag=2;
}elseif($user_dzongkhag=='Dagana'){
$user_dzongkhag=3;
}elseif($user_dzongkhag=='Gasa'){
$user_dzongkhag=4;
}elseif($user_dzongkhag=='Haa'){
$user_dzongkhag=5;
}elseif($user_dzongkhag=='Lhuntse'){
$user_dzongkhag=6;
}elseif($user_dzongkhag=='Monggar'){
......
........
Try switching these two lines, you may be deleting the select box value before it is stored in user_dzongkhag.
$(document).ready(function(){
$('#user_dzongkhag').change(function(){
$('#user_geog').html('<option> Fetching...</option>'); <-------------
var user_dzongkhag =$('#user_dzongkhag').val(); <-------------
//alert(new_div);
$.ajax({
type:"post",
data:"user_dzongkhag="+user_dzongkhag,
url:"<?php echo site_url('ajax/select_auth_geog/'); ?>",
cache:false,
success:function(resp){
//alert(resp);
$('#user_geog').html(resp);
}
});
});
});