Having ajax trouble when it comes to displaying a selected option - php

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

Related

Chrome select box not displaying the selected value on page load

This one continues to throw me for a loop...only in Chrome is this happening.
I have an "upgrade page" where a user can click a plan and then go to a form. I pass the ?plan=# here and then make it select the option that fits. For some reason, in Chrome, it IS selecting it as it shows in inspect element...however, it does not display in the select box.
I am trying a bunch of different ways to make this work in chrome, with jquery, php, html, anything I can think of, but nothing seems to be working.
Here is the jquery code:
$(document).ready(function() {
var split = location.search.replace('?', '').split('=')
var getPlan = split[1];
console.log(getPlan);
if (getPlan == 1) {
$("#memberPlan").val('premium');
} else {
$("#memberPlan").val('vip');
}
function vip() {
var list = "";
list = "<option value=\"3\">VIP: per month ($9.00)</option>\n";
list += "<option value=\"4\">VIP: every 6 months ($47.00)</option>\n";
list += "<option value=\"5\">VIP: per year ($89.00)</option>\n";
$("#service").html(list);
}
function premium() {
var list = "";
list = "<option value=\"0\">Premium: per month ($5.00)</option>\n";
list += "<option value=\"1\">Premium: every 6 months ($27.00)</option>\n";
list += "<option value=\"2\">Premium: per year ($49.00)</option>\n";
$("#service").html(list);
}
var currentPlan = $("#currentPlan").text().toLowerCase();
$('#memberPlan').attr("value", currentPlan);
if ($("#memberPlan").val() == "premium") {
premium();
}
if ($("#memberPlan").val() == "vip") {
vip();
}
$("#memberPlan").change(function() {
if ($("#memberPlan option:selected").val() == 'vip'){
vip();
}
if ($("#memberPlan option:selected").val() == 'premium'){
premium();
}
});
});
and here is the html/php ($payPlan is $_GET['plan']):
<select name="member_plan" id="memberPlan">
<option value="premium"<?php echo $payPlan == 1 ? ' selected':''; ?>>Premium</option>
<option value="vip"<?php echo $payPlan == 2 ? ' selected':''; ?>>VIP</option>
</select>
Thanks in advance, any help is appreciated :)
Try this
$("#memberPlan").change(function() {
if ($(this).val() == 'vip'){
vip();
}
if ($(this).val() == 'premium'){
premium();
}
});
Sometimes I find the "on" handler binds to the element with more consistent behavior. Try?
$("#memberPlan").on('change', function() {
if ($(this).val() == 'vip'){
vip();
}
if ($(this).val() == 'premium'){
premium();
}
});

Google map show marker not working when called you dropdown select using ajax

I have a contact page where they have multiple branches in countries. So trying to filter the location and on city select it should show the marker with info window. My problem is if I select the city directly it works but when going thru the filer dropdown it doesnt work. Please advice on what am I doing wrong.
This is my link http://www.safarikidindia.com/demo_map.html
here is my code
On country drop down I call onchange='generatestate(this)'> & generate city on state drop down. here is the ajax function code
function generatestate(o)
{
set_current_date_time()
http.abort();
document.getElementById('locationstate').innerHTML = '';
document.getElementById('locationcity').innerHTML = '';
var url = "common_ajax.php?action=showstate&countryid="+o.options[o.selectedIndex].value;
//alert(url);
http.open("GET", url, true);
http.onreadystatechange=function() {
if(http.readyState == 4) {
//alert(http.responseText);
//var response = http.responseText;
document.getElementById('locationstate').innerHTML = http.responseText;
// alert(http.responseText);
}
}
http.send(null);
}
function geneeratecity(o)
{
set_current_date_time()
http.abort();
document.getElementById('locationcity').innerHTML = '';
var url = "common_ajax.php?action=geneeratecuty&stateid="+o.options[o.selectedIndex].value;
//alert(url);
http.open("GET", url, true);
http.onreadystatechange=function() {
if(http.readyState == 4) {
//alert(http.responseText);
//var response = http.responseText;
document.getElementById('locationcity').innerHTML = http.responseText;
//alert(http.responseText);
}
}
http.send(null);
}
////////////////////////////////
In common_ajax we have following php function
if($action=="showstate")
{
$countryid = trim(filter_var($_REQUEST['countryid'], FILTER_SANITIZE_STRING));
$state = $safari->country_state_location($countryid);
?>
<select name="city" id="city" class="drpdown" onchange="geneeratecity(this);">
<option value="">Select State</option>
<?php
for($i=0;$i<count($state);$i++)
{
$statename = $safari->get_singlestate($state[$i]['state'])
?>
<option value="<?php echo $statename[0]['statesrno'];?>"><?php echo $statename[0]['statename'];?></option>
<?php
}
?>
</select>
<?php
}
if($action=="geneeratecuty")
{
$stateid = trim(filter_var($_REQUEST['stateid'], FILTER_SANITIZE_STRING));
$locations = $safari->country_city_location($stateid);
?>
<select name="city" class="city" id="city">
<option value="" selected>--- Select ---</option>
<?php
for($l=0;$l<count($locations);$l++)
{ ?>
<option value="marker<?php echo $locations[$l]['srno'];?>"><?php echo $locations[$l]['city'];?></option>
<?php } ?>
</select>
<?php
}
?>
The change-listener is bound to the #city-element that exists when you call initialize. When you filter the lists, this element will be overwritten, the newly created select will not listen to the listener.
There may be different ways to fix it, but you already use jQuery, so I would suggest to use jQuery's on() instead of google.maps.event.addDomListener :
jQuery(document).on('change','#city',
function(){
//your code
}
);

Retrieve HTML drop down list value with AJAX

I have an HTML dropdown list which i'm populating from a database. My question is how can i retrieve the value of a selected item from this dropdown list using AJAX?
My javascript:
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "/display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
The dropdown list in display-product.php:
<div>
<?php
echo '<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">';
while($row1 = $result->fetch_assoc()){
echo '<option value="' . $row1['id'] . '">' . $row1['category'] . '</option>';
}
echo '</select>';
?>
</div>
The div to display the selected item:
<div class="product_directory" id="div1"></div>
I'm not very conversant with AJAX. I tried to access the "str" variable passed to the getData function in my PHP script using "$string = $_GET['q']" but still didn't work. Thanks in advance for the help.
UPDATE: i was able the figure out the source of the problem: I have two functions that populate the select lists from the database. When a user selects an option from the first dropdown(with id="categoriesSelect"), the second one(id = "subcatsSelect") is automatically populated. Here is the code for both functions:
<script type="text/javascript">
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
The code works fine if i manually put in the select list . But using these two functions to pull from the database, nothing is displayed. I call the loadCategories() function like this
<body onload = "loadCategories()">.
The other select box is very similar to this one.
I don't know the specific issue but i know it's coming either from loadCategories() or updateSubCats().
It seems your code is retrieving the value on the select. But it fails on your function.
I tried using that open function Here. But, in my side it didn't work using an slash (/). So, try to remove that and try it.
...
xhr.open("GET", "display-product.php?q="+str, true);
...
EDIT: full working code...
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="div1"></div>
... on display-product.php
echo $_GET['q'];
Try this for the edited part of your question.
And this other to make it work together.
Hope this helps.
You can use a this possible solution with JQuery:
Add the attribute "id" in option tag in php code and remove onChange function:
echo "<select id='mySelect' title='Select one' name='selectcat'>";
Add Jquery File JQuery 1.9.1 and add the javascript HTML tag
Put before close tag body:
$(document).ready( function() {
$('#mySelect').change(function(){
var $selectedOption = $(this).find('option:selected');
var selectedLabel = $selectedOption.text();
var selectedValue = $selectedOption.val();
alert(selectedValue + ' - ' + selectedLabel);
$('.product_directory').html(selectedValue + ' - ' + selectedLabel);
$.ajax({
type:"POST",
url:"display-product.php",
data:selectedValue OR selectedLabel,
success:function(response){
alert('Succes send');
}
})
return false;
});
});
Read in php:
echo $_POST['selectedValue'];
or
echo $_POST['selectedLabel'];

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!

javascript capture all listbox values for php

I have a page that lets people assign items to a category and javascript that lets user move as many items as desired from one box on left to one on right and back so that users can preview and fine tune choices (which end up in right box). It might be better if the items could be moved between lists instead of listboxes, but select box, I guess, is good for selecting uponclick. When user is done, I need to post items in right box to php script. However, am having trouble figuring out how to capture all the items in the right list. There is no form in the script so can't get it from document.form. Items are not really selected, they just populate list and I want to get them all. Is there a variable that has the whole list? Script is lengthy so here are functions that do work. Essentially I need a way to write out list of elements in right box at end. Thanks for any suggestions.
function moveToRightOrLeft(side) {
var listLeft = document.getElementById('selectLeft');
var listRight = document.getElementById('selectRight');
if (side == 1) {
if (listLeft.options.length == 0) {
alert('You have already assigned all items to the category');
return false;
} else {
var selectedItem = listLeft.options.selectedIndex;
move(listRight, listLeft.options[selectedItem].value, listLeft.options[selectedItem].text);
listLeft.remove(selectedItem);
if (listLeft.options.length > 0) {
listLeft.options[0].selected = true;
}
}
} else if (side == 2) {
if (listRight.options.length == 0) {
alert('The list is empty');
return false;
} else {
var selectedItem = listRight.options.selectedIndex;
move(listLeft, listRight.options[selectedItem].value, listRight.options[selectedItem].text);
listRight.remove(selectedItem);
if (listRight.options.length > 0) {
listRight.options[0].selected = true;
}
}
}
}
function move(listBoxTo, optionValue, optionDisplayText) {
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
First, I think you have an error in your syntax. To get the value of the selected item of a select box, you would use something like:
var value = listLeft.options[listLeft.selectedIndex].value;
To write out all the options in a particular select box, you should be able to do something like this:
var options = document.getElementById('selectRight').options;
for (i=0; i<options.length(); i++)
document.write("value "+ i +" = "+ options[i].value);
I reworked your code a tiny bit and here is a complete working example:
<html>
<head>
<style type="text/css">
select
{
width:100px;
}
</style>
<script type="text/Javascript">
function moveToRightOrLeft(side)
{
if (side == 1)
{
var list1 = document.getElementById('selectLeft');
var list2 = document.getElementById('selectRight');
}
else
{
var list1 = document.getElementById('selectRight');
var list2 = document.getElementById('selectLeft');
}
if (list1.options.length == 0)
{
alert('The list is empty');
return false;
}
else
{
var selectedItem = list1.options[list1.selectedIndex];
move(list2, selectedItem.value, selectedItem.text);
list1.remove(list1.selectedIndex);
if (list1.options.length > 0)
list1.options[0].selected = true;
}
return true;
}
function move(listBoxTo, optionValue, optionDisplayText)
{
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
function showContents(listBoxID)
{
var options = document.getElementById(listBoxID).options;
for (var i = 0; i < options.length; i++)
alert("Option "+ options[i].value +" = "+ options[i].text);
}
</script>
</head>
<body>
<select id="selectLeft" multiple="multiple">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<button onclick="moveToRightOrLeft(2)"><</button>
<button onclick="moveToRightOrLeft(1)">></button>
<select id="selectRight" multiple="multiple">
</select>
<button onclick="showContents('selectRight')">Show Contents</button>
</body>
</html>

Categories