Ajax not returning full results - php

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>";
}

Related

Showing readily selected data in cascade drop-down list

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

How to store ajax value in php variable?

I want to store ajax value 'when selected' stored in php variable.
<select name="client_name" onchange="ajaxReq('product_name', this.value);">
<option>- - -</option>
<option value="SANY">SANY</option>
<option value="MBFC">MBFC</option>
</select>
<span id="slo_product_name"> </span>
<span id="slo_release_no"> </span>
<script type="text/javascript">
var ar_cols = ["client_name","product_name","release_no",null]; var preid = "slo_";
</script>
I've tried this, but didn't succeeded.
$releasenu=$_POST['release_no'];
How should i store the ajax value of release_no in php variable? Is there any other way?
function ajaxReq(col, wval) {
removeLists(col);
if(wval!='- - -' && wval!='') {
var request = get_XmlHttp();
var php_file = 'select_list.php';
var data_send = 'col='+col+'&wval='+wval;
request.open("POST", php_file, true);
document.getElementById(preid+col).innerHTML = 'Loadding...';
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data_send);
request.onreadystatechange = function() {
if (request.readyState==4) {
document.getElementById(preid+col).innerHTML = request.responseText; }
} } }
According to your code, you should use this in your select_list.php script:
$col = $_POST['col'];
$wval = $_POST['wval'];
// now you can use those variables to save to DB, or get some data out of DB
I assume you want to have cascade <select> elements, you should change your ajaxReq() function:
function ajaxReq(col, wval) {
// first remove all selects that are after this one
var remove = false;
var next = null; // we also need to trap next select so we can fill it
for (i in ar_cols) {
if (ar_cols[i] == col) {
remove = true; // from now on, remove lists
} else if (remove) { // if ok to remove
if (!next) {
next = ar_cols[i]; // now we found next column to fill
}
if (ar_cols[i]) { // remove only non null
removeLists(ar_cols[i]);
}
}
}
if(wval!='- - -' && wval!='' && next) { // also if there is column after to fill
var request = get_XmlHttp();
var php_file = 'select_list.php';
var data_send = 'col='+col+'&wval='+wval+'&next='+next; // also add next param
request.open("POST", php_file, true);
document.getElementById(preid+col).innerHTML = 'Loadding...';
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data_send);
request.onreadystatechange = function() {
if (request.readyState==4) {
// we fill next select
document.getElementById(preid+next).innerHTML = request.responseText;
}
}
}
}
Your select_list.php should look something like this:
$col = $_POST['col']; // this is just a filter for values in next <select>
$wval = $_POST['wval'];
$next = $_POST['next']; // we need to get this param or we cannot setup next <select>
// using $col and $wval variables get values from DB
echo '<select name="' . $next . '" onchange="ajaxReq(\'' . $next . '\', this.value);">';
foreach ($data as $row) {
echo '<option ...>...</option>'; // fix this to work for you
}
echo '</select>';
// Code changed due to bug found
The ajax request should contain one more parameter (next column) since the returned <select> should have name and onchange event prepared for next, not the currently changed.
Check the code above again.

Having ajax trouble when it comes to displaying a selected option

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);

How can I run a mysql query when the user selects an new option in a select field?

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.

Populate select with jQuery and PHP

I have a table that includes the taxonomic name of a species. So there are separate columns for each species, domain, kingdom, phylum, etc. I am using a select boxes for each of these classifications, and what I need to happen is when the first one (Domain) is selected, the database is queried to get all the kingdomes where domain is the value of the previous select.
Here's what I have for my PHP in 'search.php':
<select name="domain" id="domain">
<option value="standard">-- Domain --</option>
<?php while($row = mysql_fetch_array($get_domains, MYSQL_NUM))
{
echo "<option value='$row[0]'>$row[0]</option>";
} ?>
</select>
<select name="kingdom" id="kingdom" >
<option value="standard">-- Kingdom --</option>
<?php
$result = array();
$domain = $_POST['domain'];
$get_kingdoms = mysql_query("SELECT DISTINCT sci_kingdom FROM tbl_lifedata WHERE sci_domain = $domain");
while($row = mysql_fetch_array($get_kingdoms, MYSQL_NUM))
{
$result[] = array(
'name' => $row[0]
);
}
echo json_encode($result);
?>
</select>
And this is what I have in my jquery:
$('#domain').change(function() {
$domain = $('#domain option:selected').val();
if ($domain == 'standard') {
$('#kingdom').attr('disabled', 'disabled');
$('.btn-cover').text('Select a Domain:');
} else {
$('#kingdom').removeAttr('disabled', 'disabled');
$('.btn-cover').text('Select a Kingdom:');
}
});
$('#kingdom').change(function() {
$kingdom = $('#kingdom option:selected').val();
if ($kingdom == 'standard') {
$('#domain').removeAttr('disabled', 'disabled');
$('#phylum').attr('disabled', 'disabled');
$('.btn-cover').text('Select a Kingdom:');
} else {
$('#domain').attr('disabled', 'disabled');
$('#phylum').removeAttr('disabled', 'disabled');
$('.btn-cover').text('Select a Phylum:');
$.post("search.php", {
'domain': option
}, function(data) {
var sel = $("#kingdom");
sel.empty();
for (var i = 0; i < data.length; i++) {
sel.append('<option>' + data[i].name + '</option>');
}
}, "json");
}
});​
I'm having the most trouble understanding how the .post() function works. I know exactly what I want to do, just not exactly how to do.
My goal:
- obtain the value of the domain select box when it is changed
- use that value in the mysql query to get the relevant kingdoms
- execute the query using jquery and then populate the kingdom select box
Thanks!

Categories