passing 2 values from dropdown in php using ajax - php

I have been creating a system as a project on school. I have encountered a problem in getting values using ajax. I wanted to get values from the qselCampus dropdown and the qselCollege dropdown, then pass its values to a php file and use it on a query that will populate the third dropdown. The problem is, I cannot get the right values on the third dropdown. I am just a beginner in PHP and AJAX.
Here is my AJAX code:
$(document).ready(function() {
$("#qselBranch").change(function() {
var branchid = $(this).val();
if(branchid != "") {
$.ajax({
url:"getprof.php",
data:{txtbid:branchid},
type:'POST',
success:function(response) {
var resp = $.trim(response);
//console.log(resp);
$("#qselProf").html(resp);
}
});
} else {
$("#qselProf").html("<option value=''>------- Select --------</option>");
}
});
});
$(document).ready(function() {
$("#qselCollege").change(function() {
var collegeid = $(this).val();
if(collegeid != "") {
$.ajax({
url:"getprof.php",
data:{txtcid:collegeid},
type:'POST',
success:function(response) {
var resp = $.trim(response);
console.log(resp);
$("#qselProf").html(resp);
}
});
} else {
$("#qselProf").html("<option value=''>------- Select --------</option>");
}
});
});
Here is my PHP Code:
<?php
if(isset($_POST['txtbid'])){
$strGetValue = mysqli_real_escape_string($objConn, $_POST['txtbid']);
$strGetValue2 = mysqli_real_escape_string($objConn, $_POST['txtcid']);
echo $strGetValue;
$strStmtGetProf = "SELECT
strTeacherInfoID
, strFirstName
, strMiddleName
, strLastName
, strCampus
FROM tblteachers
WHERE strCampus = '$strGetValue' AND strCollege = '$strGetValue2'";
$objResult = mysqli_query($objConn, $strStmtGetProf) or trigger_error("Query Failed! SQL: Error: ".mysqli_error($objConn), E_USER_ERROR);
echo "<option value=''>------- Select --------</option>";
//echo $strGetValue2;
while($objFetch = mysqli_fetch_array($objResult)){
$strTID = $objFetch['strTeacherInfoID'];
$strFirstName = $objFetch['strFirstName'];
$strLastName = $objFetch['strLastName'];
$strCampus = $objFetch['strCampus'];
//echo $strGetValue;
echo '<option value="' . $strTID . '">' .$strLastName. ", " .$strFirstName. " | Branch: " .$strCampus. '</option>';
}
}
?>
And here is the HTML part:
<div class="form-row col-md-8">
<label>Campus Branch
<select name="qselBranch" id="qselBranch" required class="form-control">
<option value="">------- Select --------</option>
<option value="Bansud">Bansud</option>
<option value="Bataan">Bataan</option>
<option value="Biñan">Biñan</option>
<option value="Cabiao">Cabiao</option>
<option value="Lopez">Lopez</option>
<option value="Mabini">Mabini</option>
<option value="Maragondon">Maragondon</option>
<option value="Mulanay">Mulanay</option>
<option value="Parañaque">Parañaque</option>
<option value="Pulilan">Pulilan</option>
<option value="Quezon">Quezon</option>
<option value="Ragay">Ragay</option>
<!--<option value="Sablayan">Sablayan</option>-->
<option value="San Juan">San Juan</option>
<option value="San Pedro">San Pedro</option>
<option value="Sta. Maria">Sta. Maria</option>
<option value="Sta. Rosa">Sta. Rosa</option>
<option value="Sto. Tomas">Sto. Tomas</option>
<option value="Taguig">Taguig</option>
<option value="Unisan">Unisan</option>
</select>
</label>
</div>
<div class="form-row">
<label>
College/Faculty:
<select name="qselCollege" required class="form-control">
<option value="">------- Select --------</option>
<option value="CAF">College of Accountancy and Finance (CAF)</option>
<option value="CAFA">College of Architecture and Fine Arts (CAFA)</option>
<option value="CAL">College of Arts and Letters (CAL)</option>
<option value="CBA">College of Business Administration (CBA)</option>
<option value="COC">College of Communication (COC)</option>
<option value="CCIS">College of Computer and Information Sciences (CCIS)</option>
<option value="COED">College of Education (COED)</option>
<option value="CE">College of Engineering (CE)</option>
<option value="CHK">College of Human Kinetics (CHK)</option>
<option value="CL">College of Law (CL)</option>
<option value="CPSPA">College of Political Science and Public Administration (CPSPA)</option>
<option value="CSSD">College of Social Sciences and Development (CSSD)</option>
<option value="CS">College of Science (CS)</option>
<option value="CTHTM">College of Tourism, Hospitality and Transportation Management (CTHTM)</option>
</select>
</label>
</div>

Right now, you have 2 different Ajax call and you use both data in your php...even if you send them one by one. First, try to make ONE ajax call when you change a value in your form and if you have two value different than " ". It should look like this :
JS :
$(document).ready(function() {
$("#qselBranch, #qselCollege").change(function() { // On change for each form
var branchid = $("#selBranch").val();
var collegeid = $("#qselCollege").val();
if(branchid != "" && collegeid != "") { // check if both value are not empty
$.ajax({
url:"getprof.php",
data:{txtbid:branchid,txtcid:collegeid}, // send both value in one time
type:'POST',
success:function(response) {
var resp = $.trim(response);
//console.log(resp);
$("#qselProf").html(resp);
}
});
} else {
$("#qselProf").html("<option value=''>------- Select --------</option>");
}
});
});
PHP :
<?php
// I change nothing, juste add a double $_POST condition
if(isset($_POST['txtbid']) && isset($_POST['txtcid'])){
$strGetValue = mysqli_real_escape_string($objConn, $_POST['txtbid']);
$strGetValue2 = mysqli_real_escape_string($objConn, $_POST['txtcid']);
echo $strGetValue;
$strStmtGetProf = "SELECT
strTeacherInfoID
, strFirstName
, strMiddleName
, strLastName
, strCampus
FROM tblteachers
WHERE strCampus = '$strGetValue' AND strCollege =
'$strGetValue2'";
$objResult = mysqli_query($objConn, $strStmtGetProf) or trigger_error("Query Failed! SQL: Error: ".mysqli_error($objConn), E_USER_ERROR);
echo "<option value=''>------- Select --------</option>";
//echo $strGetValue2;
while($objFetch = mysqli_fetch_array($objResult)){
$strTID = $objFetch['strTeacherInfoID'];
$strFirstName = $objFetch['strFirstName'];
$strLastName = $objFetch['strLastName'];
$strCampus = $objFetch['strCampus'];
//echo $strGetValue;
echo '<option value="' . $strTID . '">' .$strLastName. ", " .$strFirstName. " | Branch: " .$strCampus. '</option>';
}
}
?>
Is it what you are looking for? Tell me if it works please :)

Related

How can I extract id attribute in the same file to be used in query

In my website I have drop down box and I made event to know which element selected from the user .. and it works .
I can retrieve the value and print it on the screen using id attribute !!
This function will work when user Select from drop down
<script>
function SelServ(){
var x = document.getElementById("services").value;
document.getElementById("chosenServ").innerHTML =x;
}
</script>
The drop down box reads from database
echo "<select name = \"services\" id = \"services\" onchange = \"SelServ()\">";
//my connection
$myCon = new mysqli("localhost","root","","mss");
if(mysqli_connect_errno()){
printf("Connect Failed : %s\n",mysqli_connect_error());
}
else{
$sql = "SELECT ServID ,ServName FROM service";
$result = mysqli_query($myCon,$sql);
if($result){
while($StaffArr = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$servName = $StaffArr['ServName'];
$ServiceID = $StaffArr['ServID'];
echo "<option value = \"".$ServiceID."\">".$servName."</option>";
}
}
else{
printf("Couldn't retrive records ! <br /> %s",mysqli_error($myCon));
}
}
echo "</select>";
And I'm using div to retrieve selected item
$servIDHTML = "<div id = \"chosenServ\"></div>";
I want to extract the value of id and included in sql statement to affect in seconed drop down box in the same page !!
Any idea?
You must use ajax:-
Let's say you have 2 dropdown parent_id and children:-
<select name="parent_id" id="parent_id">
<option value="">Select ID</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="child" id="child">
<option value="">Select Children</option>
</select>
Include the following ajax at the bottom of your page:-
<script>
$('#parent_id').change(function(){
var parentId = $('#parent_id').val();
$.ajax({
url: "ajax.php",
type: "post",
data: {parentId: parentId},
success: function(data) {
$('select#child').html(data);
}
});
});
</script>
PHP file where you can execute the SQL query based on your selection and return the result in options:-
ajax.php
if($_POST){
$parentId = $_POST['parentId'];
$sql = "SELECT * FROM TABLENAME WHERE parent_id=".$parentId;
/*
Fetch the result, prepare options for select and echo them
*/
}

jquery ajax submit only submitting first value

I am submitting a form using jquery and ajax. I have my first select menu and depending on the value of this select menu a div that contains a different menu will become visible.
<table>
<tr>
<td>
<select required="" class="input-medium" id="foulTypes" name="foul" data-original-title="" title="">
<option value="">Select Foul</option>
<option value="85">AID - Aiding Runner</option>
<option value="1">BAT - Illegal Bat</option>
<option value="2">BBW - Block Below Waist</option>
<option value="3">BOB - Blocking Out of Bounds</option>
<option value="4">CHB - Chop Block</option>
</select>
</td>
</tr>
</table
<script>
var foulTypes = $('#foulTypes');
var select = this.value;
foulTypes.change(function () {
//We first disable all, so we dont submit data for more than 1 category
$("#catDPI, #catILF, #catOPI, #catOH, #catDH, #catILD, #catUNS, #catUNR, #catTGT").hide().find(".category").attr("disabled", true);
var $divSelectedCategory;
if ($(this).val() == '1') {
$divSelectedCategory = $("#catDPI");
$('#catDPI').show();
} else {
$('#catDPI').hide();
}
if ($(this).val() == '85') {
$divSelectedCategory = $("#catILF");
$('#catILF').show();
} else {
$('#catILF').hide();
}
if ($(this).val() == '2') {
$('#catOPI').show();
$divSelectedCategory = $("#catOPI");
} else {
$('#catOPI').hide();
}
//We now enable only for the selected category
$divSelectedCategory.show().find(".category").attr("disabled", false).val('');
});
</script>
<div id="catDPI" style="display:none;">
<select name="category" id="dpiCategory" class='category' style="width:210px;">
<option value="Playing Through Receiver">Playing Through Receiver</option>
<option value="arm bar">arm bar</option>
<option value="Grabbing">Grabbing</option>
</select>
</div>
<div id="catILF" style="display:none;">
<select name="category" id="ilfCategory" class='category' style="width:210px;">
<option value="">Select</option>
<option value="moving">Moving</option>
<option value="illegal">Illegal</option>
<option value="standing">Standing</option>
</select>
</div>
<div id="catOPI" style="display:none;">
<select name="category" id="opiCategory" class='category' style="width:210px;">
<option value="">Select</option>
<option value="restrict">Restrict</option>
<option value="holding">Holding</option>
</select>
</div>
The foulTypes .change function is working and the correct div is being displayed. The problem I am having is when I submit the form. If the #catDPI is visible the category menu selected value is submitted fine. If #catILF or #catOPI is visible the value for category is blank. I am not using the Ids of the category menus.
$("#submit-foul").submit(function(e){
e.preventDefault();
var category = $(".category").val();
var dataString = 'category=' + category;
if($("#submit-foul").valid()){
$.ajax({
url: 'myUrl',
type: 'POST',
success: function(data){
if(data == 1){
alert('Success');
};
}
});
}
return false;
});
I am not sure what I am doing wrong. Time to send it to the experts!! I appreciate all your help.
Try to change function "foulTypes" and add class in visible select.
foulTypes.change(function () {
//We first disable all, so we dont submit data for more than 1 category
$("#catDPI, #catILF, #catOPI, #catOH, #catDH, #catILD, #catUNS, #catUNR, #catTGT").hide().find(".category").attr("disabled", true);
var $divSelectedCategory;
if ($(this).val() == '1') {
$divSelectedCategory = $("#catDPI");
$('#catDPI').show();
$('#dpiCategory').addClass("visible");
} else {
$('#catDPI').hide();
$('#dpiCategory').removeClass("visible")
}
.... CONTINUE
In your ajax submit..
var category = $(".category.visible").val();

hold values of dropdown using ajax

there are two drop downs naming country and state.....so how to hold the values whwn error occurs in the form.i have used ajax to list the state value
<select name="country" onchange="getstate(this.value,'')">
<option value="">Select</option>
<?php $option="";
$query="select * from tbl_country";
$res=mysql_query($query);
while ($country=mysql_fetch_array($res)) {?>
<option value="<?php echo $country['id']; ?>"><?php echo $country['country']; ?></option>
<?php }?>
</select>
<select id="state" >
</select>
/////ajax code///////
<script type="text/javascript">
function getstate(id) {
$.ajax({
type : 'post',
url : 'ajax.php',
data : {
act : 'get_state',
country : id,
},
success : function(data) {
data = data.replace(/\s*\n\s*/g, '');
if (data) {
document.getElementById('state').innerHTML = data;
} else {
}
return true;
}
});
}
</script>
///////ajax.php/////
if($_REQUEST['act']=="get_state"){
$statelist=array();
$countryid=$_REQUEST['country'];
$query="select * from tbl_state where id_country=".$countryid;
$result=mysql_query($query);
$option.='<option value="">select</option>';
while ($state=mysql_fetch_array($result)) {
$option.= '<option value="'.$state["state"].'">'.$state["state"].'</option>';
}
echo $option;
}
I want to hold both the values of country and state at the time of form submit(error occurs). how to do that?

javascript disable multiselect box based on selections in another multiselect box

I have two multi select boxes one for country list and one for state list
<select multiple="multiple" name="country[]" id="country" >
<option value="0">Select a Country</option>
<?php
foreach($country_list as $key=>$value){
echo "<option value=\"$key\"";
if($html['Country Name']==$key|| $row['Country Name']==$key){
echo ' selected="selected"';
}
echo ">$value</option>\n";
}?>
</select>
<select multiple="multiple" name="state[]" id="state">
<option value="">Select a State</option>
<?php
foreach($state_list as $key=>$value){
echo "<option value=\"$key\"";
if($html['state']==$key|| $row['state']==$key){
echo ' selected="selected"';
}
echo ">$value</option>\n";
}?>
</select>
I have this javascript which enables the state box when the country selected is USA.
window.onload = function() {
var selectCountry = document.getElementById('country');
selectCountry.onchange = function() {
document.getElementById('state').disabled = (selectCountry.value != 'USA')? true : false;
};
};
But, I want the state box to be disabled when other countries are selected along with USA in the first one.
Any suggestions please? Thanks
Demo: http://jsfiddle.net/eBTgb/
$("#country").on("click change", function(){
var option_usa = $("option[value=6]", this);
if (option_usa.is(":selected") && option_usa.siblings(":selected").length == 0) {
$("#state").removeAttr("disabled");
}
else {
$("#state").attr("disabled", "disabled");
}
});
I hope understand you correctly.
This can be done using JQuery.
$("#state").hide();
$("#country").change( function () {
var countryName = $("#country").find("option:selected").html();
if(countryName == 'USA'){
$("#state").show();
} else {
$("#state").hide();
}
});
Heres the link to the JSFIDDLE

Control multiple-select box using a single select box using javascript

`<select multiple="multiple" name="state[]" id="state">
<option value="">Select a State</option>
<?php
foreach($state_list as $key=>$value){
echo "<option value=\"$key\"";
if($html['state']==$key|| $row['state']==$key){
echo ' selected="selected"';
}
echo ">$value</option>\n";
}?>
</select> </p>`
<p>Select A Country
<select name="country" id="country">
<option value="0">Select a Country</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
</select> </p>
I have two select boxes 1)state[] 2) country . What is want is that "If the selected country is not USA, disable the multi-select box which consists all the USA states". Any help is appreciated
Add this Javascript to your code:
<script type="text/javascript">
<!--
window.onload = function() {
var selectCountry = document.getElementById('country');
selectCountry.onchange = function() {
document.getElementById('state').disabled = (selectCountry.value != 'USA')? true : false;
};
};
//-->
</script>
You could do the following if you have jQuery:
$('#country').change(function () {
if($('#country').val() != "USA") {
$('#state').attr('disabled', 'disabled');
}
else {
$('#state').removeAttr('disabled');
}
});
Or if you are using plain JavaScript:
var elem = document.getElementById("country");
elem.onchange = function () {
if(elem.options[e.selectedIndex].value != "USA") {
document.getElementById('state').disabled = "disabled";
}
else {
document.getElementById('state').removeAttribute("disabled");
}
}
This will disable the state combo box when the country combo box contains a value that is not "USA". When the selected country is "USA", it will remove the disabled attribute and make it usable again.
Hope this helps.

Categories