Ajax working with Javascript - php

Hi All
I am working in a PHP project. I am stucked with an issue related with Ajax.
I have A select box for Company on whose selection department is displayed using ajax, and on selection of department from department select box along with another User group select box I get the list of users.
Now on change of User group I Send request to server using ajax as user group id and department id to fetch the respective users. But when I reselect the department I cannot get the new user list as this department list is generated from ajax and Ajax do not handle Javascript.
Code I Am Working With:
select box to select company
<select name="companyname" id="companyname" onchange="javascript:dochange(this.value);">
<option value="-1">-----Select Company-----</option>
<?php foreach($user_obj->getUserCompanyname() as $key => $value){
$selected = '';
if($value['company_id'] == $user_obj->user_company_id){
$selected = 'selected="selected"';
}
?>
<option value="<?php echo $value['company_id'];?>"
<?php echo $selected;?>><?php echo $value['company_name'];?></option>
<?php }?>
Javascript to execute ajax
<script>
//Inint_AJAX funnction is excluded as it has to do anything with requirement
function dochange(val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById('selectdepartment').innerHTML="";
document.getElementById('selectdepartment').innerHTML=req.responseText; //retuen value
}
}
};
req.open("GET", "company.php?val="+val); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}
</script>
company.php
$val=$_GET['val'];
echo "<select name='departmentname' id='departmentname'>\n";
echo "<option value='-1'><b>Select Department</b></option>\n";
foreach($user_obj->getUserDepartmentname($val) as $k=>$vals){
echo "<option value='".$vals['department_id']."'>".$vals['department_name']."</option>";
}
echo "</select>\n<br>";
echo " <span class='asterisk>NOTE:Please (Re)Select the User Group everytime you change department.</span>";
User Group Select Box
<select name="usergroupname"
onchange="javascript:dochangereport(this.value,document.getElementById('departmentname').value);
dochangeoverride(this.value,document.getElementById('departmentname').value);" id="usergroupname">
<option value="-1">Select User Group</option>
<?php
foreach($user_obj->getUserGroupName() as $gkey=>$gval){
$gselect = '';
if($gval['usergroup_id'] == $user_obj->user_group_id){
$gselect = 'selected="selected"';
}
?>
<option value="<?php echo $gval['usergroup_id'];?>"
<?php echo $gselect;?>><?php echo $gval['usergroup_name'];?>
</option>
<?php }?>
</select>
function calling ajax call
<script>
function dochangereport(val,dep) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById('selectreport').innerHTML="";
document.getElementById('selectreport').innerHTML=req.responseText; //retuen value
}
}
};
req.open("GET", "reportto.php?val="+val+"&dep="+dep); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}
</script>
**reportto.php**
$val=$_GET['val'];
$dep=$_GET['dep'];
echo "<select name='reportingto[]' multiple='multiple' size='3'>\n";
echo "<option value='-1'><b>Select Supervisor(s)</b></option>\n";
foreach($user_obj->getUserReportingto($val,$dep) as $rkey=>$rval){
echo "<option value='".$rval['user_id']."'>".$rval['user_fname']." ".$rval['user_fname']." </option>";
}echo "</select>\n";
could someone help me out in this?

I'm going to guess here: you are probably using something like
$('select.department').change(function() { (...ajax...)});
Instead, use:
$('select.department').live('change', function() { (...ajax...)});
This will also match any elements that are added later and match your jQuery selector. See also: http://api.jquery.com/live/.
EDIT:
Ok, so I guessed wrong. If you're not using jQuery, you will have to use event bubbling (http://www.quirksmode.org/js/events_order.html) (EDIT: apparently, onchange doesn't bubble in IE, see Does the onchange event propagate?) or add the event handler to the newly created <select> each time you update it, using
if (req.status==200) {
document.getElementById('selectreport').innerHTML="";
document.getElementById('selectreport').innerHTML=req.responseText; //retuen value
document.getElementById('reportingto').onchange = function() {
var val = this.value,
department = document.getElementById('departmentname').value;
dochangereport(val, department);
dochangeoverride(val, department);
}
}
And then add an id to your ajaxed selectbox, like this:
(reportto.php)
echo "<select id='reportingto' name='reportingto[]' multiple='multiple' size='3'>\n";
Good luck!

I found the other way round...
I Just changed the ajax caling functiona as
I just change the container ID to select box ID
function dochange(val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById('departmentname').innerHTML="";
document.getElementById('departmentname').innerHTML=req.responseText; //retuen value
}
}
};
req.open("GET", "company.php?val="+val); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}
And changed company.php file to
$val=$_GET['val'];
echo "<option value='-1'><b>Select Department</b></option>\n";
foreach($user_obj->getUserDepartmentname($val) as $k=>$vals){
echo "<option value='".$vals['department_id']."'>".$vals['department_name']."</option>";
}
And Hence gave me all required result..

Related

Getting value from dynamically created pop up menu

I have a menu that is dynamically created. When the user selects a value, I need to get that value and use it for a query statement. This is not a form, just a menu on the page.
I have:
<select name="topic" id="topic">
<option value="optiont" selected="selected">Select topic...</option>
<?php
while ($row = mysqli_fetch_array($sql))
{
echo "<option value=\"optiont$count\" name=\topic[]\">" . $row['topic'] . "</option>";
$count++;
}
?>
</select>
I want to know which option is selected. How can I do this??
This will get the value when you change the DDL:
$('#topic option').on("change", function () {
var opt_ID = $(this).val();
//Do something here using opt_ID as the value e.g.
window.location = '/URL/file.php?' + opt_ID;
});
Try this:
jquery:
var selvalue = $("#topic option:selected").val();
$.get( "demo.php?value="+selvalue, function(data) {
alert(data);
});
Demo.php:
<?php
$sel = $_GET['value'];
// write your query here
?>

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'];

Language configuration (change url and refresh page on DropDown change)

I am setting up a multilanguage website.
I have a dropdown where there is a set of languages that I cover.
I would like script, when dropdown changes, add or replace variable to url and refresh the page.
I do not want to store language in session or cookie.
My goal is that search egnines indexes all my multilanguage pages and to have url rewritting so my URL would look like http://www.index.php/EN/home, which I will cover later.
Currently I have a DropDown which sumbits form on change:
echo "<select name='lang' onchange='this.form.submit()'>";
$array = oci_parse($conn, "SELECT code, name FROM languages");
oci_execute($array);
while ($row = oci_fetch_array($array))
{
if ($lang == $row[0])
{
echo "<option value=".$row[0]." selected='selected'>".$row[0]."</option>";
}
else
{
echo '<option value='.$row[0].'>'.$row[0].'</option>';
}
}
echo '</select>';
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<select name='lang' id="dropdown">
<option value="EN">English</option>
<option value="FR">French</option>
</select>
<script>
$('#dropdown').change(function()
{
var langValue = $('#dropdown').val(); // i.e. langValue='EN' or langValue='FR'
if(langValue)
{
window.location.href = 'http://www.index.php/' + langValue + '/home';
return true;
}
return false;
});
function addLang(langValue)
{
var url = window.location.href;
var urlP = url.split('/');
if(urlP.length <4)
{
url = url + langValue; // adding new lang
}
else
{
url[3] = langValue; // replace old lang
url = url.join('/');
}
console.log(url);
}
</script>
Try this,
$(document).ready(function(){
$('#form').submit(function()
{
var lang=$("[name='lang']")val();
window.location.href='http://www.index.php/' + lang+ '/home';
}
});
});

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

Categories