I am having a trouble with populate a drop-down value from another drop-down with AJAX database. So basically there are Intake and Courses in my form. So, if user choose Intake A, then courses PHP and JQuery will be in Courses option. My problem is now, after i choose Intake A, Courses option doesn't give any value. Can you please help me? Thanks
Here is the AJAX CODE
$(document).ready(function($) {
var list_target_id = 'Courses'; //first select list ID
var list_select_id = 'Iname'; //second select list ID
var initial_target_html = '<option value="">Please select intake...</option>'; //Initial prompt for target select
$('#'+list_target_id).html(initial_target_html); //Give the target select the prompt option
$('#'+list_select_id).change(function(e) {
//Grab the chosen value on first select list change
var selectvalue = $(this).val();
//alert(selectvalue);
//Display 'loading' status in the target select list
$('#'+list_target_id).html('<option value="">Loading...</option>');
if (selectvalue == "") {
//Display initial prompt in target select if blank value selected
$('#'+list_target_id).html(initial_target_html);
} else {
//Make AJAX request, using the selected value as the GET
$.ajax({url: 'CoursesDropdown.php?svalue='+selectvalue,
success: function(output) {
//alert(output);
$('#'+list_target_id).html(output);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " "+ thrownError);
}});
}
});
});
Here is the PHP side
<?php
include "connect.php";
$selectvalue = mysqli_real_escape_string($con, $_GET['svalue']);
$checkuser = "Select Coursesname from courses Where CoursesIntake ='$selectvalue'";
$result2 = mysqli_query($con, $checkuser);
echo '<option value="">Please select...</option>';
echo $result2;
while ($row = mysqli_fetch_array($result2)) {
//echo '<option value=" . $row["CoursesName"] . "> . $row["CoursesName"] . "</option>"';
//echo '<option value=' . $row['Coursesname'] . '>' . $row['Coursesname'] . '</option>';
echo '<option value="">Please select...</option>';
echo '<option value="">Please select...</option>';
}
mysqli_close($con);
?>
Related
This question already has answers here:
select2 jquery plugin not working after ajax calling for HTML content change
(2 answers)
Closed 3 years ago.
I have one initial dropdown, where I want to select a value:
<select id="indexID" name="indexID" class="form-control" onChange="updateSector();" style="width:300px;">
<option value='' selected>Select and Index</option>
<option value='3'>AIM</option>
<option value='1'>FTSE 100</option>
<option value='2'>FTSE 250</option>
</select>
When a different value is selected it runs the updateSector() function, which uses an ajax script to load all the sectors which are relevant for the selected category. The output from the page investment_sectors is then displayed in a tag on the page.
function updateSector(){
<? if ($sectorID<>""){?>
var sectorID = <?=$sectorID?>;
<? }else{?>
var sectorID = "";
<?}?>
var indexID = document.getElementById("indexID");
var indexID = indexID.options[indexID.selectedIndex].value;
var dataString = 'indexID=' + indexID +'§orID=' + sectorID;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "investment_sectors.php",
data: dataString,
cache: false,
success: function(html) {
//alert(html);
document.getElementById("sector").innerHTML = html;
}
});
}
This all works if I want to generate a standard select dropdown of the sectors. But as there are many sectors, I really want a select2 field.
Normally, if I was just including the select2 field in a standard page, I'd add this script to the bottom to load any passing values I want preselected. However, as the tag is empty until an option is selected and passed back, there is nothing to populate.
<script>
$(document).ready(function() {
$('.js-example-basic-single').select2();
});
$(document).ready(function() {
var select2single = $('.js-example-basic-single').select2({
placeholder: "Please Select",
width: '400px',
multiple: false,
})
select2single.val([<?=$sectorID?>]);
select2single.trigger("change");
});
</script>
Can anyone help me adapt my code to generate this select2 field, rather than a standard select dropdown?
Thanks
This is the code in the called investment_sector page:
$sectorID=$_REQUEST['sectorID'];
$indexID=$_REQUEST['indexID'];
switch ($indexID){
case "1":
$sectorlist = "FTSE";
break;
case "2":
$sectorlist = "FTSE";
break;
case "3":
$sectorlist = "AIM";
break;
default:
$sectorlist = "";
}
$query = "SELECT * FROM tbl_sector WHERE sectorlist='".$sectorlist."' order by sector ASC";
$result = mysqli_query( $conn, $query )or showError( mysqli_query( $conn, $query ) );
$num_rows = mysqli_num_rows( $result );
echo "<select class=\"js-example-basic-single js-states form-control\" id=\"sectorID\" name=\"sectorID\">";
if ($sectorID==""){
echo "<option value='' selected>Select a ".$sectorlist." sector</option> \n ";
}
$i = 0;
while ( $row = mysqli_fetch_array( $result ) ) {
if ( $sectorID == $row[ 'sectorID' ] ) {
echo "<option value='" . $row[ 'sectorID' ] . "' selected>".$row[ 'sectorlist' ]." - " . $row[ 'sector' ] . "</option> \n ";
} else {
echo "<option value='" . $row[ 'sectorID' ] . "'>".$row[ 'sectorlist' ]." - " . $row[ 'sector' ] . "</option>\n";
}
$i++;
}
echo "</select>";
The problem is that you only initialize select2 when your document is ready. For elements that are created in the DOM afterwards, it won't automatically happen, even if they have the same class. You should reinitalize select2 for the new elements when your ajax is completed. Try this:
$.ajax({
type: "POST",
url: "investment_sectors.php",
data: dataString,
cache: false,
success: function(html) {
//alert(html);
document.getElementById("sector").innerHTML = html;
$('#' + sectorID).select2();
}
});
I have two select boxes in which I want to select a value for one and the second select box should get same value.
Currently I am passing id and want my designation also to pass to ajax. Can I know how this can be implemented via ajax. Any help will be highly appreciated.
<select name="designation" class="form-control" id="desig" >
<option value="">Select a Designation/Role</option>
<?php
$sql = mysql_query("SELECT id, designation FROM tbl where status =1 and designationtype_id = 1 ");
while ($rows = mysql_fetch_assoc($sql)){
echo "<option value=" . $rows['id'] . ">" . $rows['designation'] . "</option>";
}
?> <select name="dd" id="dd" class="form-control" disabled>
<option value=""></option>
</select>
My AJAX,
<script type="text/javascript">
$(document).ready(function() {
$("#desig").change(function() {
var id = $(this).val();
var dataString1 = 'id=' + id;
var des = $(this).val();
var dataString2 = 'designationname=' + des;
$.ajax({
type: "POST",
url: "escalation_ajax.php",
data: dataString,
cache: false,
success: function(html) {
var data = html.split(",");
$('#rephead').val(data[0]);
}
});
});
});
</script>
escalation_ajax.php
<?php
if ($_POST['id'])
{
if ($_POST['des'])
{
$des_id = $_POST['id'];
$designation = $_POST['des'];
$sql = mysql_query("SELECT designation_id, reporting_head FROM aafmindia_in_sbi.tbl_reporting_head WHERE status=1 and reporting_head_for='$des_id'");
if ($sql === FALSE)
{
trigger_error('Query failed returning error: ' . mysql_error() , E_USER_ERROR);
}
else
{
while ($row = mysql_fetch_array($sql))
{
$id = $row['designation_id'];
$reporting_head = $row['reporting_head'];
echo '<option value="' . $id . '">' . $reporting_head . '</option>' . ',' . '<option value="' . $des_id . '">' . $designation . '</option>';
}
}
}
}
?>
What you could do, is have the second select (the one that needs the same value as the first) in a seperate file that you load via AJAX.
AJAX function:
function selection()
{
var selectValue=$("select#dd option:selected").val();
$.ajax({
type : "POST",
url : "escalation_ajax.php",
data : { id : selectValue },
success: function (html) {
$("#secondSelectorDiv").html(html);
}
})
}
What this does, is that when the selection() function is called, it will post the selected value of the first select to "escalation_ajax.php". It will then load that page into an element (div element in my example) with the id "secondSelectorDiv".
The html for the select with the function (which I will call onchange in this example), can look like this:
<select id="dd" onchange="selection();">
<option value=""></option>
</select>
<div id="secondSelectorDiv"></div>
Now in escalation_ajax.php you can retrieve the post variable and use it to look for the id in question for the second select.
<?php
$id=$_POST['id'];
/*
If you're using the id to fetch something in your database,
which it looks like you're doing, then use the post variable
to fetch your rows and build the select from that.
*/
$sql="SELECT * FROM table_name WHERE id='$id'";
$result_set=mysql_query($sql);
$row=mysql_fetch_array($result_set);
$count=mysql_num_rows(result_set);
$counter=0;
//this is the id you will check for in order to see what's to be selected
$idToCheck=$row['id'];
?>
<select id="dd2">
while($count > $counter)
{
counter++;
echo '<option value=""'; if($idToCheck == $id){ echo 'selected="selected"'; } echo '></option>';
}
?>
If you want the second select to be displayed before the first select has a value, you can simply just call an AJAX function that loads in the second select on page load.
IMPORTANT!: You should really switch to mysqli_* or PDO instead of using the deprecated mysql_*. You should at the very least look into sanitizing your inputs.
i am trying to populate second dropdown based on the selected option of 1st dropdown but i am unable to do so i dont know what i am doing wrong but something is wrong all my endeavors to achieve my desired results are dashed to the ground cuz its not working kindly help me
so far i have done this....
<select name="ddl_company" size="1" class="form-control" id="ddl_company" onchange="getId(this.value);">
<option value="">Select Company</option>
<?php
//Getting Company name from mysql and displaying it in the 1st dropdown having id ddl_company
$query = mysql_query("select * from company where company_status='Active'order by company_name asc");
while ($r = mysql_fetch_array($query)) {
if ($r['company_id'] == $ddl_company) {
echo "<option selected value=$r[company_id]>$r[company_name]</option>" . "<BR>";
} else {
echo "<option value=$r[company_id]>$r[company_name]</option>";
}
// second drop down list which is going to fetch data from mysql db based on the selected option of 1st dropdown
?>
<select name="ddl_dept" size="1" class="form-control" id="ddl_dept">
<option value=""></option>
</select>
//ajax implementation of 2nd dropdown
<script type="text/javascript">
function getId(val)
{
$.ajax({
type:"POST",
url:"getdata.php",
data:"company_id="+val,
success:function(data)
{
$('#ddl_dept').html(data);
}
});
}
</script>
finally get_data.php file
<?php
include("../newconfig.php");
if (!empty($_POST['company_id'])) {
$company_id = $_POST['company_id'];
$query = "select * from department where department_status='Active'LIMIT 1 AND company_id='$company_id'LIMIT 1";
$sqlquery = mysql_query($query);
while ($r = mysql_fetch_array($sqlquery)) {
# code...
if ($r['company_id'] == $company_id) {
echo "<option selected value=$r[department_id]>$r[department_name]</option>" . "<BR>";
} else {
echo "<option value=$r[department_id]>$r[department_name]</option>";
}
}
}
}
?>
I have done all this yet its not working kindly help me i shall be very thankful. btw thats my output
click this to show the result
Try something like this : jquery
$("select#ddl_dept").on('change',function(){
var selected = $('#ddl_company option:selected').text();
getId(selected );
});
I have two select box and want to populate 2nd select box based on onchange of first select box. so my code for first select box
<select id="category-box" name="category" onchange="showCrops()" >
<option value ="0">Select category</option>
<?php
$query = $con->query("Select*from categories");
while($row = $query->fetch_object())
{
echo "<option value = '".$row->category_id."'>".$row->category."</option>";
}
?>
</select>
onchange function for ajax call
function showCrops() {
var name = $('#category-box').val();
$.ajax({
type: "POST",
url: "getCropName.php",
data: {category:name},
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
var opts = $.parseJSON(data);
$.each(opts, function(i,d) {
$('#crop-box').append('<option value="' + d.crop_id + '">' + d.crop_name + '</option>');
});
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(textStatus);
}
});
}
php code to get response
header('Content-type: text/html; charset=utf-8');
include("connect.php");
$category = $_POST['category'];
$sql1 = $con->query("SELECT category_id from categories where category ='".$category."' ");
$row1= $sql1->fetch_array();
$sql2 = $con->query("SELECT * from crop_category where category_id ='".$row1['category_id']."' ");
while($row2 = $sql2->fetch_assoc()){
echo json_encode($row2);
}
json response is
{"crop_id":"1","category_id":"1","crop_name":"rice"} {"crop_id":"2","category_id":"1","crop_name":"wheat"}
but i'm getting 'parsererror' on main php page. Whats the problem in my code ? i have less knowledge in javascript so maybe need correction to populate by 2nd select box.
Just change the php code, so the right JSON string is generated ..
$arr = array();
while($row2 = $sql2->fetch_assoc()){
$arr[] = $row2;
}
echo json_encode($arr);
I have three select boxes on a page and when someone selects an option from the 1st box, I want to update the options via ajax for the 2nd box. When someone updates the 2nd box then the 3rd box gets new options via ajax.
The problem I'm having seems to be that when the user updates the first box, I check the DB for the options I need and then in php create the new select box and replace the original one. The problem is, even though the code for the select box is the same, and the id's the same the original javascript which was watching for a change on this 2nd box no longer works.
here's the cakephp/html all the cake stuff is doing is creating select boxes.
<table>
<tr>
<td class="threeCol"><?php echo $this->Form->input('industry', array('type'=>'select', 'options'=>$industries, 'empty'=>'Industry', 'id'=>'industry', 'class'=>'formInputSelect'));?></td>
<td class="threeCol" id="cateWrap"><?php echo $this->Form->input('category', array('type'=>'select', 'options'=>$categories, 'empty'=>'Category', 'id'=>'category', 'class'=>'formInputSelect'));?></td>
<td class="threeCol" id="courseWrap"><?php echo $this->Form->input('course', array('type'=>'select', 'options'=>$courses, 'empty'=>'Course', 'id'=>'course', 'class'=>'formInputSelect'));?></td>
</tr>
</table>
And the javascript I use:
<script type="text/javascript">
$(document).ready(function() {
//Update categories dropdown when inustry selected
$("#industry").change(function() {
if( this.value != "Industry" ) {
$.post("<?php echo $this->webroot;?>categories/selectoptionsupdate", {id:this.value})
.done(function (data) {
$("#cateWrap").html(data);
});
}
});
//Update course dropdown when category selected
$("#category").change(function() {
if( this.value != "Category" ) {
$.post("<?php echo $this->webroot;?>courses/selectoptionsupdate", {id:this.value})
.done(function (data) {
$("#courseWrap").html(data);
});
}
});
});
And finally the php which creates the new box.
//UPdate the options for the dropdown on post new job page
function selectoptionsupdate() {
if ($this->request->is('ajax')) {
$this->layout = 'ajax';
$id = $this->request->data['id'];
$options = $this->Course->find('list', array('conditions'=>array('Course.category_id'=>$id)));
$result = '';
$result .= '<select name="data[Job][course]" id="course" class="formInputSelect">';
$result .= '<option value="">Course</option>';
foreach($options as $k=>$v) {
$result .= '<option value="'.$k.'">'.$v.'</option>';
}
$result .= '</select>';
echo 'hey';
}
}
Whats the best way round this problem?
change the lines
$("#industry").change(function() {
$("#category").change(function() {
for:
$(document).on("change", "#industry", function() {
$(document).on("change", "#category", function() {
http://api.jquery.com/on/