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.
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'm trying to fetch mutiple values from database using ajax php.
I've a select option(value is fetching from database), and if i select any option then i want to display the related data which is matching with the id
of the the current option.but currently i'm able to fetch only one data column from databse.
I'm writing my current code please have a look at it and let me know how can i modify it.
My select option:-
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' onChange="getCity(this.value);" id="vno" required='true' >
<option value="">Select</option>
<?php
foreach($results as $vd) { ?>
<option value='<?php echo $vd['id'];?>'><?php echo $vd['vno'];?></option>";
<?php } ?>
</select>
and the js file
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:'id='+val,
success: function(data){
$("#rate").html(data);
}
});
}
retrive_data.php
<?php
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
$query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
$results = $db_handle->runQuery($query);
?>
<?php
foreach ($results as $city) {
?>
<option value="<?php echo $city["rate"]; ?>"><?php echo $city["rate"]; ?></option>
<?php
}
}
?>
Change your js code as below
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php?id=" + val,
success: function(data){
$("#rate").html(data);
}
});
}
I’m making some assumptions about the desired result, and I’m not sure what the connection is between vehicles and city rates... but there are multiple issues here. Let’s work through them:
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' id="vno" required='true' >
<option value="">Select</option>
<?php foreach($results as $vd): ?>
<option value="<?= $vd['id']?>" ><?= $vd['vno'] ?></option>";
<?php endforeach; ?>
</select>
<!-- add a landing spot for the data coming in -->
<select id="rate"></select>
Nothing major here, just took out the onChange (typical practice is to have a listener in the JavaScript. Separation of concerns)
In your JavaScript, I don’t think you were successfully passing the id. It should be a JavaScript object. Also, send data to a function that knows how to put the data in your form:
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:{id: val},
success: function(data){
showRate(data);
}
});
}
Monitor the select for a change. (JavaScript should be inside document ready block)
$('#vno').on('change', function (){
getCity($(this).val());
});
Function to display the results of your ajax call:
showRate(data) {
// this lets you see the data that was returned
console.log(data);
var rate = $('#rate');
// clear current content
rate.html('');
// create options, assuming this is a select
$.each(data, function() {
rate.append($("<option />").val(this.rate).text(this.rate));
});
}
retrieve.php
Need to use prepared statements, and sending data as json instead of html is recommended
<?php
// sending json (data), not html (presentation)
header('Content-Type: application/json');
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
// substituting variables in a query is a big no-no
// $query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
// must use placeholders / prepared statement
$query = "SELECT * FROM tbl_vehicle WHERE id = ?'";
// check your database object for how to do prepared statements and row fetching. If it doesn’t do prepared statements, dump it!
$stmt = $db_handle->prepare ($query);
$stmt->execute($_POST["id"]);
$out = array();
while($row = $stmt->fetch() ) {
$rate = $row['rate'];
$out[] = array(
'rate'=>$rate
);
}
die(json_encode($out));
}
Caveat: all code is off the top of my head, and typed on a phone. Syntax errors are likely. This is intended to show concepts and ideas for further research
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 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);
?>
I am trying to populate an initial customer select box with results from PDO MySql via PHP. Then I would like the second contact select box to update with additional information related to what was chosen in the first box. I can't get the second script to work. I think the problem is in my ajax script because the PHP scripts work fine when ran on there own.
The Primary Script
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#contact").change(function(){
var cid = $("#cid").val();
$.ajax({
type:"post",
url:"contact.php",
data:"cid="+cid,
success: function(data) {
$("#contact").html(data);
}
});
});
});
</script>
</head>
<body>
Campaign :
<select name="customer" id="customer">
<option>-Select a Customer-</option>
<?php
include ("function.php");
include("connect.php");
$id = $_SESSION['profile']['id'];
foreach($db->query("SELECT * FROM customers WHERE pid = '$id'") as $row) {
echo "<option value=" . $row['id'] . ">" . $row['name'] . "</option>";
}
?>
</select>
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
</body>
</html>
The Contact script
include("connect.php");
$cid = $_POST["cid"];
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
Maybe your second function should start on #customer change
I see you used the contact select in ajax not customer as you described. However the code you wrote, you used the contact selector with change event, But the contact select box contain only one value, How can it change ??
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
The previous select should has more than option to can change. Or I think you mean the #customer instead contact as following:-
$("#customer").change(function(){
// your code;
});
Why not just encode a JSON response with the ids and names?
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
$arr[] = array("id" => $row['id'], "name" => $row['name']);
}
echo json_encode($arr);
Then in your ajax response, you could do
$(document).ready(function () {
$("#customer").change(function () {
var cid = $("#customer").val();
$.ajax({
type: "post",
url: "contact.php",
data: {cid: cid},
success: function (data) {
var options = [];
$.each(data, function () {
options.push('<option value="' + this.id + '">' + this.name + '</option>');
});
$("#contact").html(options.join(""));
}
});
});
});