I have made a cascade dropdown list for choosing country and city (depending on the country chosen) for users to update their profiles.
In the earlier version where users choose country and city works ok. But since this will be a update profile page, I want to show already selected data if the data is not null.
It works ok for the country selection but couldn't figure out how to implement this already selected data to trigger the javascript because second dropbox only triggered with a selection on the first dropdown.
Any help is appreciated!
Here is the javascript part
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //fuction to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCity(countryId) {
var strURL="findCountry.php?country="+countryId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Here is the php part:
<?php
$username = $_SESSION[ 'username' ];
$sql = $conn->query( "SELECT * FROM users WHERE username='$username' " );
if ( $sql->num_rows > 0 ) {
// output data of each row
while ( $info = $sql->fetch_assoc() ) {
echo '
<select id="country" name="country" onchange="getCity(this.value)" required>
<option value="" selected disabled hidden>Country</option>';
$sql2 = $conn->query( "SELECT * FROM world_countries ORDER BY country_name ASC" );
// output data of each row
if ( $info[ 'country' ] != null ) {
echo '<option value="' . $info[ "country" ] . '" selected>' . $info[ "country" ] . '</option>';
}
while ( $row = $sql2->fetch_assoc() ) {
echo '<option value="' . $row[ "cc_iso" ] . '">' . $row[ "country_name" ] . '</option>';
}
echo '<div id="citydiv"><select name="city"><option>Select Country First</option></select></div>';
}}
?>
And here is the findCountry.php:
<?
require_once("config.php");
$country=$_GET['country'];
$sql=$conn->query("SELECT * FROM world_cities WHERE id='$country' ORDER BY full_name_nd ASC");
if ( $sql->num_rows > 0 ) {
echo '
<select name="cities">
<option>Select City</option>';
while($row=$sql->fetch_assoc()) {
echo '<option value="'.$row['full_name_nd'].'">'.$row['full_name_nd'].'</option>';
}
echo '</select>';
} else {
echo 'error';
}
$conn->close();
?>
You should add a second GET parameter to your ajax request to get the options with one already selected, like:
function getCity(countryId, selected = "none") {
var strURL="findCountry.php?country="+countryId+"&selected="+selected;
var req = getXMLHTTP();
//...
In your PHP add selected to the correct option:
<?
require_once("config.php");
$country=$_GET['country'];
$selected = $_GET['selected'];
$sql=$conn->query("SELECT * FROM world_cities WHERE id='$country' ORDER BY full_name_nd ASC");
if ( $sql->num_rows > 0 ) {
echo '
<select name="cities">
<option>Select City</option>';
while($row=$sql->fetch_assoc()) {
$status = "";
if($selected!="none" && $row['full_name_nd'] == $selected) //apply selection
$status = "selected";
echo '<option value="'.$row['full_name_nd'].'" '.$status.'>'.$row['full_name_nd'].'</option>';
}
echo '</select>';
} else {
echo 'error';
}
$conn->close();
Now you should be able to call your function passing the selected city at page load
Related
I have code to return options for a dropdown box from a query. I have the function set up and the code it's grabbing from. When I check the appraisal_options.php page it shows the correct amount of items in the dropdown, but when I go to the page that is calling it, it doesn't show any of the results from the query lines. It does return the 'test' result that's manually coded.
function loadMake(dropdown_type) {
const xhttp = new XMLHttpRequest();
xhttp.onload = function () {
document.getElementById( "make" ).innerHTML = this.responseText;
}
xhttp.open( "GET", "appraisal_options.php?type=" + dropdown_type, true );
xhttp.send();
}
/// Get results for Make from Type
if ( $_GET['type'] ) {
$type = $_GET[ "type" ];
echo "<select id='make' name='make'> <option value='none' selected> Select a Make</option>";
$make_query = mysqli_query( $con, "SELECT DISTINCT Make FROM UnitsOptions WHERE Type = '$type'" )or die( mysqli_error() );
while ( $return = mysqli_fetch_array( $make_query ) ) {
echo "<option onclick='loadYear()' value='".$return['Make']. "'>".$return['Make']."</option>";
}
echo "<option value='none' onclick='loadYear()'> test</option> </select>";
}
I've a php page where there is a ajax concatenate select and a div with the total number of records in the table tb1
HTML
<p>
<select name="model" id="model">
<?php echo $myclass->selModel(); ?>
</select>
</p>
<br />
<p>
<select name="year" id="year">
<option value=""> </option>
</select>
</p>
<p>
<div id="total"><?php echo $myclass->recordNum();?></div>
</p>
JS
// VARS
var wait = '<option>Waiting</option>';
var select = '<option value="">Select</option>';
// CAT_1 //
$("select#model").change(function(){
var model = $("select#model option:selected").prop("value");
$("select#year").html(wait);
$.post("ajax-php/select-concat.php", {model:model}, function(data){
switch (data) {
case select:
$("select#year").html("");
return false;
default:
$("select#year").prop("disabled", false);
$("select#year").html(data);
return false;
}
});
});
PHP - select-concat.php
if(isset($_POST['model']))
{
echo $myclass->selYear();
die;
}
MY PHP CLASS
public function selYear() {
$result = $this->db->mysqli->query
("SELECT year FROM tb1 WHERE model='$_POST[model]");
$year = '<option value="">Select</option>';
while($row = $result->fetch_assoc()) {
$year .= '<option value="' . $row['year'] . '"';
$year .= '>' . $row['year'] . '</option>';
}
return $year;
}
private function recordNum(){
$result = $this->db->mysqli->query
("SELECT * FROM tb1 WHERE something ");
$numrec = $result->num_rows;
return $numrec;
}
My goal is to update the number of records with ajax every time I run a concatenate select. How could I do that? Thanks
You should use json_encode() on select-concat.php to return two results.
if(isset($_POST['model']))
{
$years = $myclass->selYear();
$total = $myclass->recordNum();
$arr = array('years' => $years, 'total' => $total);
echo json_encode($arr);
die;
}
You must add POST model value to recordNum() function (or pass it with an argument).
Then...
$("select#model").change(function(){
var model = $("select#model option:selected").prop("value");
$("select#year").html(wait);
$.post("ajax-php/select-concat.php", {model:model}, function(data){
var json_data = $.parseJSON(data);
switch (data) {
case select:
$("select#year").html("");
$("#total").html(0);
return false;
default:
$("select#year").prop("disabled", false);
$("select#year").html(json_data.years);
$("#total").html(json_data.total);
return false;
}
});
});
I am terribly failing with an ajax/jquery piece of code I am trying to learn in order to solve a predicament I have.
Below is my ajax:
$('#sessionsDrop').change( function(){
var search_val = $(this).val();
$.post("addstudentsession.php",
{studenttextarea : search_val},
function(data){
if (data.length>0){
$("#studentselect").html(data);
}
});
At the moment I am keeping getting a blank page everytime I load my addstudentsession.php script. This is the only script I am working on so I am not sure if I am suppose to link the ajax to itself. But below is what I am trying to do:
I have a drop down menu below:
<select name="session" id="sessionsDrop">
<option value="">Please Select</option>
<option value='20'>EWYGC - 10-01-2013 - 09:00</option>
<option value='22'>WDFRK - 11-01-2013 - 10:05</option>
<option value='23'>XJJVS - 12-01-2013 - 10:00</option>
<option value='21'>YANLO - 11-01-2013 - 09:00</option>
<option value='24'>YTMVB - 12-01-2013 - 03:00</option>
</select> </p>
Below I have a Multiple Select box where it displays a list of students that is taking the select assessment from the drop down menu above:
$studentactive = 1;
$currentstudentqry = "
SELECT
ss.SessionId, st.StudentId, st.StudentAlias, st.StudentForename, st.StudentSurname
FROM
Student_Session ss
INNER JOIN
Student st ON ss.StudentId = st.StudentId
WHERE
(ss.SessionId = ? and st.Active = ?)
ORDER BY st.StudentAlias
";
$currentstudentstmt=$mysqli->prepare($currentassessmentqry);
// You only need to call bind_param once
$currentstudentstmt->bind_param("ii",$sessionsdrop, $stuentactive);
// get result and assign variables (prefix with db)
$currentstudentstmt->execute();
$currentstudentstmt->bind_result($dbSessionId,$dbStudentId,$dbStudentAlias,$dbStudentForename.$dbStudentSurname);
$currentstudentstmt->store_result();
$studentnum = $currentstudentstmt->num_rows();
$studentSELECT = '<select name="studenttextarea" id="studentselect" size="6">'.PHP_EOL;
if($studentnum == 0){
$studentSELECT .= "<option disabled='disabled' class='red' value=''>No Students currently in this Assessment</option>";
}else{
while ( $currentstudentstmt->fetch() ) {
$studentSELECT .= sprintf("<option disabled='disabled' value='%s'>%s - %s s</option>", $dbStudentId, $dbStudentAlias, $dbStudentForename, $dbStudentSurname) . PHP_EOL;
}
}
$studentSELECT .= '</select>';
But I have a little problem, I need a way to be able to display the list of students in the select box when the user has selected an option from the drop down menu. The problem with the php code is that the page has to be submitted to find its results.
So that is why I am trying to use ajax to solve this but what am I doing badly wrong?
Try using ajax call as following,
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
XMLHttpRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
XMLHttpRequestObject = false;
}
}
}
$('#sessionsDrop').change( function(){
var search_val = $(this).val();
if (XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST", "addstudentsession.php", true);
XMLHttpRequestObject.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
}
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4
&& XMLHttpRequestObject.status == 200) {
y = XMLHttpRequestObject.responseText;
$("#studentselect").html(y);
}
};
};
XMLHttpRequestObject.send("studenttextarea=" + search_val);
I want to have a select box that list categories of products. When a category is selected I want to simultaneously select the products in that category from the database. Do I need to use AJAX with this application? Any examples about doing this? Here is the code I'm working with:
These functions build the options of each select field.
function buildCategoryOptions($catId = 0)
{
$sql = "SELECT cat_id, cat_parent_id, cat_name
FROM tbl_category
ORDER BY cat_id";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());
$categories = array();
while($row = dbFetchArray($result)) {
list($id, $parentId, $name) = $row;
if ($parentId == 0) {
// we create a new array for each top level categories
$categories[$id] = array('name' => $name, 'children' => array());
} else {
// the child categories are put int the parent category's array
$categories[$parentId]['children'][] = array('id' => $id, 'name' =>
$name);
}
}
// build combo box options
$list = '';
foreach ($categories as $key => $value) {
$name = $value['name'];
$children = $value['children'];
$list .= "<option value=\"$key\"";
if ($key == $catId) {
$list.= " selected";
}
$list .= ">$name</option>\r\n";
foreach ($children as $child) {
$list .= "<option value=\"{$child['id']}\"";
if ($child['id'] == $catId) {
$list.= " selected";
}
$list .= "> {$child['name']}</option>\r\n";
}
}
return $list;
}
/*
Build the product options list for the radio options
*/
function buildProductOptions($catId = 0)
{
$sql = "SELECT pd_id, pd_name, cat_id
FROM tbl_product
WHERE cat_id = $catId
ORDER BY pd_name";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());
$numProduct = dbNumRows($result);
$products = array();
while($row = dbFetchArray($result)) {
list($id, $name) = $row;
// we create a new array for each top level categories
$products[$id] = array('name' => $name);
}
// build combo box options
$list = '';
foreach ($products as $key => $value) {
$name = $value['name'];
$list .= "<option value=\"$key\"";
$list .= ">$name</option>\r\n";
}
return $list;
}
This is the page of the select fields:
$catId = (isset($_GET['catId']) && $_GET['catId'] > 0) ? $_GET['catId'] : 0;
$categoryList = buildCategoryOptions($catId);
$productList = buildProductOptions($catId);
<!--- Category Select --->
<select name="cboCategory" id="cboCategory" class="box">
<option value="" selected>-- Choose Category --</option>
<?php
echo $categoryList;
?>
</select>
<!--- Products Select : category is changed the products need to be from selected cat -
-->
<select name="selectOptions" id="selectOptions" class="box" multiple="multiple" >
<option>--Pick the other options--</option>
<?php
echo $productList;
?>
</select>
Yes you do need to use ajax here. Check following code and notes.
Write the function that returns a ActiveXObject() which would do a ajax call as
function getXMLHTTP() {
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}
}
return xmlhttp;
}
Then write a function specific to your site that would get the desired data as
function getProducts(){
var select1 = document.getElementById("cboCategory");
var strURL = "getproducts.php?city="+select1.options[select1.selectedIndex].value;
var req = getXMLHTTP(); // function to get xmlhttp object
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) { // data is retrieved from server
if (req.status == 200) { // which reprents ok status
document.getElementById('productsdiv').innerHTML = req.responseText; // div to be updated
} else {
alert("[GET Products]There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
};
req.open("GET", strURL, true); // open url using get method
req.send(null);
}
}
This function would be called on change event of the cboCategory select options, so the corresponding html would be
<select onchange="getProducts()" id="cboCategory" class="box">
...
</select>
<!-- Can be anywhere on same page -->
<div id="productdiv"> </div>
Your getproduct.php page would return a html as string that would over-write the contents of producstdiv tag in your html page.
You can also return data from php as json. Check it's tag wiki for more info. Also you can use jquery to do ajax call.
<form>
<table>
<tr>
<td>
<input type="tex" id="arheading" name="arheading" value="Article Heading" onfocus="if (this.value == 'Article Heading') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Article Heading';}" />
</td>
<td>
<select id="plaetype" name="placetype">
<option selected="Place Type">Place Type</option>
<?php
include 'ini/configs_adm.php';
$result_adm = mysql_query("SELECT * FROM places");
while($row_adm=mysql_fetch_array($result_adm))
{
echo '<option value="'.$row_adm['places'].'">'.$row_adm['places'].'</option>';
}
?>
</select>
</td>
<td>
<select id="country" name="country">
<?php
include 'ini/configs_adm.php';
$result_adm = mysql_query("SELECT * FROM countries");
while($row_adm=mysql_fetch_array($result_adm))
{
echo '<option value="'.$row_adm['country'].'">'.$row_adm['country'].'</option>';
}
?>
</select>
</td>
</tr>
</table>
</form>
Above is the code that i want to load on my index page without refreshing or without navigation through AJAX.
and the ajax code i tried to is.........
var loadedobjects = ""
var rootdomain = "http://" + window.location.hostname
function ajaxpage(url, containerid) {
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject) { // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e) {
try {
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e) {
}
}
}
else
return false
page_request.onreadystatechange = function () {
loadpage(page_request, containerid)
}
page_request.open('GET', url, true)
page_request.send(null)
}
function loadpage(page_request, containerid) {
if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1))
document.getElementById(containerid).innerHTML = page_request.responseText
}
function loadobjs() {
if (!document.getElementById)
return
for (i = 0; i < arguments.length; i++) {
var file = arguments[i]
var fileref = ""
if (loadedobjects.indexOf(file) == -1) { //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js") != -1) { //If object is a js file
fileref = document.createElement('script')
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css") != -1) { //If object is a css file
fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref != "") {
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects += file + " " //Remember this object as being already added to page
}
}
}
and the code that will call for AJAX function is.....
<ul id="admin_menu">
<?php
include 'ini/configs_adm.php';
$result_adm = mysql_query("SELECT * FROM adm_tools");
while ($row_adm = mysql_fetch_array($result_adm))
{
echo '<li>' . $row_adm['adm_menu'] . '</li>';
}
?>
</ul>
My ajax code have loaded the page but the php script is not retrieving data from db
It looks like you might be missing the extract($row) function.
That would look like:
while($row_adm=mysql_fetch_array($result_adm))
{
extract($row_adm);
echo '<option value="'.$row_adm['places'].'">'.$row_adm['places'].'</option>';
}