Ajax and PHP resending request after results have been written - php

I am a beginner in ajax and on very short deadline so I am turning to this community for help.
My problem is:
When I successful make ajax request and the results are returned I cant select another value. I will try to explain below.
I have a PHP page with search form that contains 4 dropdowns and a submit button. Goal is to set the search parameters by selecting a values from dropdowns. When you select the first value, all the others must change values according to selected value.
For example: I have a dropdowns named:
Destination, Month, Port and Ship
When you select the Destination then all the other dropdowns are rewritten in manner that correspond to the destination. So when I have this the Destination is a single, now I want to select witch month, or port or Ship I want to use and so on.
I hope you understand.
EDITED: It seems it is not the problem with ajax but with Jquery event not fiering up after ajax returns values.
The code I have is:
Ajax:
<script>
var xmlhttp;
function showUser(dest,mese,port,ladja)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="remote.php";
url=url+"?dest="+dest+"&mese="+mese+"&port="+port+"&ladja="+ladja;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
PHP
<div id="src">
<div id="main">
<div id="content">
<form name="src" id="src_form" method="post" action="result.php">
<div id="lin1" class="lin"><?php Destinacija(); ?></div>
<div id="lin2" class="lin"><?php Mesec(); ?></div>
<div id="lin3" class="lin"><?php Pristanisce(); ?></div>
<div id="lin4" class="lin"><?php Ladja(); ?></div>
<div id="lin5"><button id="src" type="submit">Išči</button></div>
</form>
</div>
</div>
</div>
<script>
$("#content").on("change", ".lin", function(event){
event.preventDefault();
//console.log( $( this ).text() );
showUser(document.getElementById('dest').value,document.getElementById('mese').value,document.getElementById('port').value,document.getElementById('ladja').value);
});
</script>
<?php include("ajax.php"); ?>
<?php
function Destinacija()
{
include("class/class.Translate_inl.php");
$tr = new Translate_inl("dest_code");
include("includes/conSql.php");
$result = mysqli_query($con,"SELECT DISTINCT region_code FROM no_air_pricing");
echo '<select name="dest" id="dest">'.PHP_EOL;
echo '<option value="0">Destinacija</option>'.PHP_EOL;
while($row = mysqli_fetch_array($result))
{
$dest = $tr->TrVar($row['region_code']);
echo'<option value="'.$row['region_code'].'">'.$dest.'</option>'.PHP_EOL;
}
echo '</select>'.PHP_EOL;
include("includes/disSql.php");
}
function Mesec()
{
$tr = new Translate_inl("meseci");
include("includes/conSql.php");
$mo = array();
$i=0;
$result = mysqli_query($con,"SELECT sail_date FROM no_air_pricing ORDER BY sail_date");
while($row = mysqli_fetch_array($result))
{
$month = explode("/",$row['sail_date']);
$mo[$i] = $month[0];
$i++;
}
include("includes/disSql.php");
$un_mo = array_unique($mo);
$un_mo = array_values($un_mo);
$k = count($un_mo);
echo'<select name="mese" id="mese">'.PHP_EOL;
echo'<option value="0">Mesec odhoda</option>'.PHP_EOL;
for($j=0; $j<$k; $j++)
{
echo'<option value="'.$un_mo[$j].'">'.$tr->TrVar($un_mo[$j]).'</option>'.PHP_EOL;
}
echo'</select>'.PHP_EOL;
unset($tr);
}
function Pristanisce()
{
$tr = new Translate_inl("port_code");
$port = array();
$i=0;
include("includes/conSql.php");
$result = mysqli_query($con,"SELECT departure_port_code FROM no_air_pricing ORDER BY departure_port_code");
while($row = mysqli_fetch_array($result))
{
$port[$i] = $row['departure_port_code'];
$i++;
}
include("includes/disSql.php");
$uport = array_unique($port);
$uport = array_values($uport);
$k = count($uport);
echo '<select name="port" id="port">'.PHP_EOL;
echo '<option value="0">Pristanišče odhoda</option>'.PHP_EOL;
for($j=0; $j<$k; $j++)
{
echo'<option value="'.$uport[$j].'">'.$tr->TrVar($uport[$j]).'</option>'.PHP_EOL;
}
echo '</select>'.PHP_EOL;
unset($tr);
}
function Ladja()
{
$tr = new Translate_inl("ladje_kode");
$ladje = array();
$i=0;
include("includes/conSql.php");
$result = mysqli_query($con,"SELECT ship_code FROM no_air_pricing ORDER BY ship_code ");
while($row = mysqli_fetch_array($result))
{
$ladje[$i] = $row['ship_code'];
$i++;
}
include("includes/disSql.php");
$uladje = array_unique($ladje);
$uladje = array_values($uladje);
$k = count($uladje);
echo '<select name="ladja" id="ladja">'.PHP_EOL;
echo '<option value="0">Ladja</option>'.PHP_EOL;
for($j=0; $j<$k; $j++)
{
echo'<option value="'.$uladje[$j].'">'.$tr->TrVar($uladje[$j]).'</option>'.PHP_EOL;
}
echo '</select>'.PHP_EOL;
unset($tr);
}
?>
Any help would be welcome. Thanks in advance.
I have edit the script code in php file, to implement the answer from Musa.
Still need help the original problem still stends.

Solved the problem.
I have puted:
$.ajaxSetup({
url: "remote.php",
global: true,
type: "POST"
});
before my ajax script and it fired up. Pleas don't ask me why, it just works ;)
Thank you for all the answers.

Related

Access values of multiple checked boxes

I want to access the values of dynamically created check boxes.
# $db = mysql_connect("abc", "abc", "");
mysql_select_db("abc");
$strSQL = "SELECT * FROM student";
$rs = mysql_query($strSQL);
$num_rows = mysql_num_rows($rs);
echo "<i style='color:#fff'> Number of Students = ".$num_rows."</i>";
$i=1;
while($r = mysql_fetch_array($rs)){
echo "<tr>";
echo "<td class='promotetabledata'>".$r[7]."</td>";
echo "<td class='promotetabledata'>".$r[6]."</td>";
echo "<td class='promotetabledata'><input type='checkbox' class='pr' value='".$r[7]."'/></td>"; /*dynamically created check boxes*/
echo "</tr>";
$i++;
}
The results are displayed in a promoteresults div using AJAX
<form id="promotionform" action="promotestudents.php" method="POST">
<div id="promoteresults">The results will show up here..!!
</div>
<div style=" position:relative; margin-top:10px; padding-left:44%;">
<button type="submit" class="button black">Promoted</a>
</div>
</form>
When the promoted button is clicked I want to get the selected records and update their value. To update the records, I need PHP. I can access the selected records in Javascript using
var selected = document.getElementsByClassName('pr').checked;
But how do I get the checked records in the HTML form and their values in PHP
The AJAX call with Javascript
function getpromotestudents()
{
//alert("hi");
var xmlhttp;
var select1 = document.getElementById('promotefacultyselect1');
var facutlyselect = select1.options[select1.selectedIndex].value;
var select2 = document.getElementById('promotedepartmentselect1');
var deptselect = select2.options[select2.selectedIndex].value;
var select3 = document.getElementById('promotecourseselect1');
var courseselect = select3.options[select3.selectedIndex].value;
var select4 = document.getElementById('promoteyearselect1');
var yearselect = select4.options[select4.selectedIndex].value;
var select5 = document.getElementById('promotesemselect1');
var semselect = select5.options[select5.selectedIndex].value;
var the_data = 'faculty='+facutlyselect+' &dept='+deptselect+' &course='+courseselect+' &year='+yearselect+' &sem='+semselect;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
/*
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("searchresults").innerHTML=xmlhttp.responseText;
}
}*/
xmlhttp.open("POST", "getpromotestudents.php", true); // set the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // adds a header to tell the PHP script to recognize the data as is sent via POST
xmlhttp.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
document.getElementById("promoteresults").innerHTML = xmlhttp.responseText;
}
}
}
<td class='promotetabledata'><input type='checkbox' name='pr[]' value='".$r[7]."'/></td>
This is the PHP code I finally wrote to access all the checkboxes, and perform the required operations on the selected ones.
<?php
$checkbox = $_POST['pr'];
foreach($checkbox as $value){
if(isset($checkbox)){
echo '<script>alert("'.$value.'")</script>';
}
}
?>
Give each of the checkbox name property like this
<input type='checkbox' class='pr' value='8' name='chk[]'/>
Than in the php you can get them as follows
<?php
$chkbox = $_POST['chk'];
foreach($chkbox as $a => $b){
echo $chkbox[$a];
}
?>
Set each check box's name property to pr[], as in:
echo "<input type='checkbox' class='pr' name='pr[]' value='".$r[7]."'/>";
Then, the first checkbox will be at $_POST['pr'][0], the second at $_POST['pr'][1] and so on.

Jquery get value of element loaded with AJAX

I have a page with 2 select boxes, one of which is loaded by an AJAX call. I then want to validate the elements with jquery before I enable the submit button. The jquery works fine when I change the static select (strDirectorate) but not when I change the one loaded by AJAX (new_cc).
Is it because jquery is getting the value of new_cc as it was when the page was loaded?
<div class="selectfield">
<select id="strDirectorate" name="strDirectorate" class="mainform_select" onChange="getNewCostCentre(this.value)">
<option value="" selected="selected"></option>
<?php do { ?>
<option value="<?php echo $row_rsLocality['strLocalityShort']?>" <?php if($row_rsLocality['strLocalityShort'] == $strDirectorate){ echo $selected; } ?>><?php echo $row_rsLocality['strLocalityLong']?></option>
<?php
} while ($row_rsLocality = mysql_fetch_assoc($rsLocality));
$rows = mysql_num_rows($rsLocality);
if($rows > 0) {
mysql_data_seek($rsLocality, 0);
$row_rsLocality = mysql_fetch_assoc($rsLocality);
}
?>
</select>
</div>
<div id="txtNewCostCentre" class="selectfield">
<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)">
<option value="" selected="selected"></option>
</select>
</div>
<div class="actions">
<input type="submit" id="submit_button" name="submit_button" class="styled_button" value="Submit" />
</div>
The function getNewCostCentre is
function getNewCostCentre(str)
{
if (str=="")
{
document.getElementById("txtNewCostCentre").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtNewCostCentre").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getNewCostCentre.php?q="+str,true);
xmlhttp.send();
}
The code for getNewCostCentre.php is
$sql="SELECT * FROM `tblcostcentreorganisation` WHERE `strOrganisation` LIKE '363 ".addslashes($dir)."%'";
$result = mysql_query($sql);
if(isset($_GET["q"])){
$display_string = '<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)" style="background-color:#F8E0E0">';
$display_string .= '<option value="" selected="selected" disabled="disabled"></option>';
}else{
$display_string = '<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)">';
}
while($row = mysql_fetch_array($result))
{
$cc = substr($row['strCostCentre'], 3, strlen($row['strCostCentre'])-3) . " " . substr($row['strOrganisation'], 3, strlen($row['strOrganisation'])-3);
$org_name = $row['strOrganisation'];
if ($org == $org_name){
$display_string .= '<option value="'.$org_name.'" selected="selected">'.$cc.'</option>';
}else{
$display_string .= '<option value="'.$org_name.'">'.$cc.'</option>';
}
}
$display_string .= '</select>';
echo $display_string;
And the jquery validation is:
$(document).ready(function() {
$('.selectfield select').change(function() {
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
});
});
The onload code is as follows. I assume it's because I'm using .load within (after) .onload?
$(document).ready(function(){
window.onload = function(){
//Load directorate, cost centre and position
if ($('#hid_stage').val() == "Rejected") {
var str = $('#hid_criteria').val();
strencoded = encodeURIComponent(str);
$('#txtNewCostCentre').load("getNewCostCentre.php?cr="+strencoded);
$('#txtNewPosition').load("getNewPosition_ba.php?cr="+strencoded);
}
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
}
});
You are binding your change handler for $('.selectfield select') when the page loads. This attaches the handler to all elements that match that selector.
If you then change this element, it won't have the handler attached.
Instead, you should use the live handler, to match all elements that exist now or are ever created in the future.
$('.selectfield select').live("change", function() {
...
});
UPDATE:
For you onload issue, it would be far easier not to repeat your code. If you need to fire off the validation after loading the content dynamically, then trigger the change event once the load has finished - like the following example:
$(document).ready(function(){
//Load directorate, cost centre and position
if ($('#hid_stage').val() == "Rejected") {
var str = $('#hid_criteria').val();
strencoded = encodeURIComponent(str);
$('#txtNewCostCentre').load("getNewCostCentre.php?cr="+strencoded, function() {
$('.selectfield select').trigger("change");
});
$('#txtNewPosition').load("getNewPosition_ba.php?cr="+strencoded);
}
});
An ajax update of the input shouldn't trigger the javascript change event so the handler you've specified in change won't get called.
From the javascript specification (http://www.w3.org/TR/html401/interact/scripts.html) :
onchange = script [CT] The onchange event occurs when a control loses
the input focus and its value has been modified since gaining focus.
This attribute applies to the following elements: INPUT, SELECT, and
TEXTAREA.
I'd suggest performing the validation logic in the same part of your javascript where you're handling the response from the ajax request. Right after the line
document.getElementById("txtNewCostCentre").innerHTML=xmlhttp.responseText;
add the call
validate();
Where validate is earlier defined as :
function validate() {
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
}
So that your jquery validation becomes:
$(document).ready(function() {
$('.selectfield select').change(validate());

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

Sending Checkbox Values to PHP page using javascript Ajax and not jQuery

I have a situation in which i need to do insert queries for every check box selected through an ajax request sent to a php script which would do the insert in mysql.
i know how to do it without an ajax call via the simple form submission with a variable like groups[] as an array and running the foreach loop in php for every value in the array.
How do i send the array a via post ajax request?
a sample code:
<input type='checkbox' name='groups[]' value='1'>Group A
<input type='checkbox' name='groups[]' value='2'>Group B
<input type='checkbox' name='groups[]' value='3'>Group C
Please help, i know this might be easy but i am just not getting it. and guys, please don't give any example of jquery or the likes as i want pure html, javascript and php solution.
Thanks community...
Here's the Javascript function:
<script type='text/javascript'>
function addResp(tid){
a = encodeURIComponent(document.getElementById('course_add_resp').value);
b = encodeURIComponent(document.getElementById('term_add_resp').value);
c = encodeURIComponent(document.getElementById('paper_add_resp').value);
var elements = document.getElementsByName('groups[]');
var data = [];
for (var i = 0; i < elements.length; i++){
if (elements[i].checked){
data.push('groups[]='+elements[i].value);
}
}
params = "tid="+tid+"&course="+a+"&sem="+b+"&paper="+c+"&grp="+data;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.body.removeChild(document.getElementById('respBackground'));
document.body.removeChild(document.getElementById('respBox'));
contents = xmlhttp.responseText;
if(contents == "done"){
window.location = "teachers.php";
} else{
document.getElementById("studentBox").innerHTML = "There was a problem serving the request.";
}
}
}
xmlhttp.open("POST","assignresp.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
}
</script>
and the php script:
<?php
$tid = mysql_real_escape_string($_POST['tid']);
$cid = mysql_real_escape_string($_POST['course']);
$sem = mysql_real_escape_string($_POST['sem']);
$paper = mysql_real_escape_string($_POST['paper']);
$session = 12;
$type = 1;
$groups = $_POST['grp'];
foreach ($groups as $value ) {
$q1 = "insert into iars(sessionid,teacherid,courseid,semester,paperid,groupid,type) values('$session','$tid','$cid','$sem','$paper','$value','$type')";
$r1 = mysql_query($q1) or die(mysql_error());
if(mysql_affected_rows() > 0){
echo "done";
}
else{
echo "fail";
}
}
?>
var elements = document.getElementsByName('groups[]');
var data = [];
for (var i = 0; i < elements.length; i++){
if (elements[i].checked){
data.push('groups[]='+elements[i].value);
}
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data.join('&'));
//for get
//xmlhttp.open("GET",url+"?"+data.join('&'),true);
//xmlhttp.send();
EDIT
Change these two lines.
params = "tid="+tid+"&course="+a+"&sem="+b+"&paper="+c+"&"+data.join('&');
$groups = $_POST['groups'];
you can do this with two way,
you can use the post type ajax call
You can get the all selected checkbox values with JavaScript make comma separated string and just pass it in one variable
that's all you can do .... :)

How to use AJAX in IE

i'm using IE and I need to do a simple AJAX that will display a table with values from the database once a dropdown has been changed.
Here is my script:
<script type="text/javascript">
function getXML()
{
var req;
try {
req = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
req = null;
}
}
}
if (!req){
return null;
} else {
return req;
}
}
function filter(month, year)
{
if(getXML()){
var xmlhttp = getXML();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("mandayTable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax/filterMandays.php?m="+month+"&y="+year,true);
xmlhttp.send();
} else {
alert("Error initializing XMLHttpRequest!");
}
}
</script>
and here is my ajax php
<?php
$q = "SELECT md.mandays_id,md.employeenum,md.month,md.year,md.required_man_days,d.firstname,d.lastname
FROM tbl_mandays md,tbl_employee_details d
WHERE md.active = '1'
AND md.employeenum = d.employeenum
AND md.month = '10';"; //employee_details WHERE approver = 0"
$res = $db->Execute($q);
echo "<table border = 1>";
echo "<tr><th>Employee Number</th><th>First Name</th><th>Last Name</th><th>Month-Year</th><th>Required Man Days</th><th>Edit/Delete</th></tr>";
/while($rows = $res->FetchRow())
for($i=0;$i<5;$i++)
{
$mandays_id = $rows[0];
$empnum = $rows[1];
$month_year = $rows[2] ."-" .$rows[3];
$required_man_days = $rows[4];
$firstname = $rows[5];
$lastname = $rows[6];
echo "<tr><td>".$empnum . "</td><td>".$firstname ."</td><td>".$lastname ."</td><td>" . $month_year ."</td><td>" .$required_man_days . "</td><td width = \"200\" align = \"center\"><a href = 'edit_mandays.php?mandays_id=$mandays_id');'>Edit/Delete</a></td></tr>";
}
echo "</table>";
?>
THe problem is that on the first "ONCHANGE" it does not do anything.
on the 2nd "ONCHANGE" the headers of the table in the php code is the only one that's being echoed.
I alsoi tried doing it without the query and changing the loop into for($i=0;$i<5;$i++) and changed the qvalues to be displayed into "1" but still it does noty go into the loo[ and display it.
what seems to be the problem? :(
Start here : https://developer.mozilla.org/en/AJAX/Getting_Started , Mozilla explains the correct way to do this across browsers. Later, you may consider jQuery for cross-browser compatibility once you've learned the basics
Download and use jQuery for your website: http://docs.jquery.com/Downloading_jQuery#Download_jQuery
And then your code will be something like this:
$('.mydropdown').change(function(){
//get values for month, year
$.ajax({
url: "ajax/filterMandays.php?m="+month+"&y="+year,
type: "GET",
success: function(data){
//data is returned back
$('#mandayTable').html(data);
}
});
});

Categories