PHP with AJAX Scripting

Dear friends,
I am coding with PHP and using AJAX to read post data read from MySQL to controls on PHP page.
But I have a small problem.

I can connect to MySql and read a field in a table, post the entire data of that field to the ComboBox Control on PHP page without re-loading the page (i.e., isPostBack=false).
Pls see the code below:

Explanation:
From an AJAX script, it uses a php file (getparish-details.php) with a string variable (strPar) and a key (parish_d).
When you select an item in a combo box, the onChange() event of the combo box calls the AJAX function and passes the value of your selection to the key of the function.
The function opens the php file getparish-details.php and reads the specified data from the mysql table.
When you read data from mysql, the getparish-details passes the data to strPar and
the document.getElementById(“txtaddress”).innerHTML=“”; declaration posts the data to the control whose ‘id’ is declared in document.getElemetById.
This will automatically call data from the database without re-loading the php page.
However, I have only been able to do this with combo box controls.
The problem I have is;
I want to post data to textbox controls instead of combo box. But I am having problems.
Pls can you assist me.

Thank you!


<script type="text/javascript">
<!--
// JavaScript Document
function loadparish_details(strPar)
{
if (strPar=="")
  {
  document.getElementById("txtphone").innerHTML="";
  document.getElementById("txtpic").innerHTML="";
  document.getElementById("txtaddress").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("txtphone").innerHTML=xmlhttp.responseText;
	document.getElementById("txtpic").innerHTML=xmlhttp.responseText;
	document.getElementById("txtaddress").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getparish-details.php?parish_d="+strPar,true);
xmlhttp.send();
}
</script>

getparish-details.php


<?php
$qd=$_GET["parish_d"]; //qd is a variable that holds a key.
//$province=$_GET['province'];
//$region=$_GET["region"];

$parish_dt = mysql_query("SELECT pic_name, address, phone FROM parish WHERE parish_name='$qd'");
//echo "<Select id='txtpro' name='province' size='1'> ";
while($row = mysql_fetch_array($parish_dt)){
//echo $row['address'];
echo '<input type="text" name="address" value="'.$row['address'].'" size="70" /><br /><br />';
//echo '<option value="'. $row['address'].'">' . $row['address'].'</option>'; }

//echo "</select> ";
//echo $combine;
?>



Morning EasyTime,

I can spot a problem with your PHP straight away:

//echo '<option value="'. $row['address'].'">' . $row['address'].'</option>'; } 

By commenting out this line, you’ve also commented out the closing brace for your while loop. You need to move the brace to a separate line.

Yea, it’s true…that’s my mistake anyway… But that is not the problem.
I commented out that line when I was testing the echo ‘<input type=“text”>’; without the while($row(something)){.
When it did not work, I forgot to return it to normal… However, see the corrected code below: but that is not the problem.
The problem is, if I

 echo '<option value="'. $row['address'].'">' . $row['address'].'</option>'; 

, it will work with combo boxes. But if I

echo '<input type="text" name="address" value="'.$row['address'].'" size="70" /><br /><br />'; 

, it will not even report an error…it does not work.
Pls see code below.

getparish-details.php file


<?php
$qd=$_GET["parish_d"];
//$province=$_GET['province'];
//$region=$_GET["region"];

$parish_dt = mysql_query("SELECT pic_name, address, phone FROM parish WHERE parish_name='$qd'");
//echo "<Select id='txtpro' name='province' size='1'> ";
while($row = mysql_fetch_array($parish_dt)){
//echo $row['address'];
echo '<input type="text" name="address" value="'.$row['address'].'" size="70" /><br /><br />';}
//echo '<option value="'. $row['address'].'">' . $row['address'].'</option>';  

//echo "</select> ";
//echo $combine;
?>

php file that has the controls


<select name="parish" id="txtparish" size="1" onchange="loadparish_details(this.value)">
</select>

Do you get any output if you go directly to the PHP page, e.g. getparish-details.php?parish_d=example_parish?

Sure, the getparish-details.php actually reads the data from the mysql table and posts it. But the data does not reflect on the textbox control on the other php page.
Meanwhile, like I said before, if I echo out combo box (<option>Item</option>), you can see the data loaded on the combo box (VB=items.add() method).
The only problem is, it does not show the data on a textbox except on a combo box.
Meanwhile, if I need to show the data on the combo box, I need to change the <select id=‘txtaddress’> so that the getElementById in the AJAX script can identify the combo box control.

Could you post the html for the elements where the data should be output to, please (i.e. elements #txtphone, #txtpic, and #txtaddress)?

<body>
<div class="page">
<div class="header">

 <div class="title">

            <table border="0" cellpadding="0" cellspacing="6" width="900px">
            <tr><td align="left" valign="top" style="width:100px;"><h1>
            <a href="/dce/"><img width="80" alt="Site Logo" height="93" src="/dce/images/mohg.gif" /></a>
            </h1></td>
            
            <td align="left" valign="top" style="width:800px;">
            <table border="0" cellpadding="0" cellspacing="0" width="100%">
            <tr>
            <td align="right" valign="top" style="width:inherit; color:#FFFFFF;">

            <img src="../images/colored5635.gif" alt="separator image" /> Contact Us:<span style="font-size:smaller; color:#fff; font-weight:bold;"> 07030602824
            </span> &nbsp;&nbsp;<img src="../images/colored5635.gif" alt="separator image" />
            Email: <span style="font-size:smaller; font-weight:bold;"><a href="mailto:info@dce.com" style="color:#fff; text-decoration:none; text-decoration:blink;">info@dce.com</a></span>            </td>
            </tr>
            <tr><td align="center" valign="top" style="width:auto;">
           <table border="0" cellpadding="0" cellspacing="0" width="800px">
           <tr>
           <td align="center" valign="middle" style="width:700px;">
		   <h1 style="color:#fff;">Directorate <i>of</i> Christian Education</h1>
           </td>
           
           <td align="center" valign="top"><br />
           <div class="loginDisplay">
		  
		   
<?php
// Set Timezone
date_default_timezone_set('America/New_York');
// What day of the week is it (Mon - Sun)
$day = date("l");
$date = date("d . m . y");
echo "Today is: " . $day . "<br>" . $date;
?> 
		   </div></td>
           </tr>
           </table>
            </td></tr>
            </table></td>

            </tr>
            </table>
    </div>
            
<div class="clear hideSkiplink">
              <div class="menu">
	
              <marquee style="color:#ffffff;" behavior="scroll" direction="left" width="100%" scrollamount="2" scrolldelay="5">
        Welcome to <a href="/dce/" style="text-decoration:underline; color:#ffffff;">the RCCG, Directorate of Christian Education. </a> 
        DCE is in charge of Sunday school, House fellowship and Children/Teens Teaching of the RCCG worldwide.
              </marquee>

            </div>
    </div>            

</div>
<div class="loginDisplay">
<!-- <p align="center"> -->
 <span style="color:#003366;">
 <img src="../images/colorf6ac9b.gif" alt="separator image" /><img src="../images/colored5635.gif" alt="separator image" /> 
[ <a href="/dce/" style="color:#003366; text-decoration:none;">Home</a> ]
<img src="../images/colored5635.gif" alt="separator image" /><img src="../images/colorf6ac9b.gif" alt="separator image" />
[ <a href="../about.php" style="color:#003366; text-decoration:none;">About DCE</a> ]
<img src="../images/colored5635.gif" alt="separator image" /><img src="../images/colorf6ac9b.gif" alt="separator image" />
[ <a href="../Accounts/register.php" style="color:#003366; text-decoration:none;">Register</a> ]
<img src="../images/colorf6ac9b.gif" alt="separator image" /><img src="../images/colored5635.gif" alt="separator image" />
[ <a href="../Accounts/login.php" style="color:#003366; text-decoration:none;">Login</a> ] <img src="../images/colored5635.gif" alt="separator image" /><img src="../images/colorf6ac9b.gif" alt="separator image" /> </span> <!-- </p> -->
 </div>
 
 <h1 style="margin-left:15px;">Parish  Registration Form </h1>
 <p align="justify" style="margin-left:15px; margin-right:20px;">This is the registration form for the parish. Each registered. <br />
 </p>
 <hr />
 <form id="form1" name="form1" action="confirm_parish.php" method="post" style="margin-left:15px; margin-right:20px;">
 <fieldset style="border-radius:5px; -webkit-border-radius:5px; -o-border-radius:5px; -moz-border-radius:5px;">
   <legend>Parish Information</legend>
   <p><b style="color:#990000;">Select Area : * </b>
   <select name="area" id="txtarea" onchange="loadparish(this.value)">
       <option value="Select your Area" selected="selected">Select your Area</option>
       <?php
/*
this file is used as a test file for the ajax function to load data from database without
reloading the page. It selects query criterion from a select option box and
passes the loaded data to another select option box.
the ajax script function is embedded in this file and 
the url the script sends a call to is getprovince.php.
This ajax script uses the getElementById("") method of javascript.
The element to be retrieved is the HTML inner element (id).
*/

$load_area = mysql_query("SELECT area_number FROM _area ORDER BY area_number");
while ($row = mysql_fetch_array($load_area)) {
  echo '<option value="'. $row['area_number'] .'">' . $row['area_number'].'</option>'; } ?>
     </select>
&nbsp;&nbsp;&nbsp;&nbsp; <b style="color:#990000;">Parish Name : *</b>
<select name="parish" id="txtparish" size="1" onchange="loadparish_details(this.value)">
</select>
&nbsp;&nbsp; <b style="color:#990000;">Month : * </b>
<select name="month" id="txtmonth">
  <option value="Select Month" selected="selected">Select Month</option>
  <option value="January">January</option>
  <option value="February">February</option>
  <option value="March">March</option>
  <option value="April">April</option>
  <option value="May">May</option>
  <option value="June">June</option>
  <option value="July">July</option>
  <option value="August">August</option>
  <option value="September">September</option>
  <option value="October">October</option>
  <option value="November">November</option>
  <option value="December">December</option>
  
  <?php
/*
this file is used as a test file for the ajax function to load data from database without
reloading the page. It selects query criterion from a select option box and
passes the loaded data to another select option box.
the ajax script function is embedded in this file and 
the url the script sends a call to is getprovince.php.
This ajax script uses the getElementById("") method of javascript.
The element to be retrieved is the HTML inner element (id).
*/?>
</select>
<br />
<br />
<b style="color:#990000">Average Attendance  : *</b> <br />
<input type="text" name="attendance" value="" class="passwordEntry" />
<br />
<br />
<b style="color:#990000"> Parish Address : *</b><br />
<input type="text" name="address" id="txtaddress" value="" class="passwordEntry" />
<b style="color:#990000"> Name of PIC : *</b>
<input type="text" name="pic" id="txtpic" value="" class="passwordEntry" />
<br />
<br />
<b style="color:#990000">Contact Phone Numbers :</b> <br />
<input type="text" name="phone" id="txtphone" value="" class="passwordEntry" />
<b style="color:#990000">Number of Births :</b>
<input type="text" name="births" id="births" value="" class="passwordEntry" />
<br />
<br />
<b style="color:#990000">No. of Marriages: *</b><br />
<input type="text" name="marriages" id="marriages" value="" class="passwordEntry" />
<b style="color:#990000">No. of Deaths  : *</b>
<input type="text" name="deaths" id="deaths" value="" class="passwordEntry" />
</p>
   <p><b style="color:#990000">No. of House Fellowships: *</b><br />
     <input type="text" name="hfellowships" id="hfellowships" value="" class="passwordEntry" />
     <b style="color:#990000">No. of Converts  : *</b>
     <input type="text" name="converts" id="converts" value="" class="passwordEntry" />
   </p>
 </fieldset>&nbsp;</p>
  
     <br />
     <br />
     <input name="btnRegister" type="submit" class="submitButton" onclick="MM_validateForm('parish_name','','R','address','','R','member_count','','NisNum','username','','R','email','','RisEmail','password','','R','con_password','','R');return document.MM_returnValue" value="Register" />
   </p>
 </form>
 <p></p>
 <h1 style="margin-left:15px;" class="">&nbsp;</h1>
 <h1 style="margin-left:15px;">&nbsp;</h1>
</div>
<div class="footer">
     <?php include_once("../footer.php");?>
   
</div>
</body>

OK, so in your JS function loadparish_details, you’ve got this code:

document.getElementById("txtphone").innerHTML = xmlhttp.responseText;
document.getElementById("txtpic").innerHTML = xmlhttp.responseText;
document.getElementById("txtaddress").innerHTML = xmlhttp.responseText;

The first problem here is that you’re assigning the ajax response to the innerHTML attribute, if you wanted to replace the element you’d have to use outerHTML:

document.getElementById("txtphone").outerHTML = xmlhttp.responseText;

The second problem is that your PHP is only sending back a string representing the address element:


while($row = mysql_fetch_array($parish_dt)){
    echo '<input type="text" name="address" value="'.$row['address'].'" size="70" /><br /><br />';
}

so your code would end up replacing all three elements with copies of the address element.

A better solution might be to just return the data you need as JSON, and update the input values. This is more efficient that sending back a string representing a chunk of HTML:


while($row = mysql_fetch_array($parish_dt)){
    echo json_encode($row);
}

var response = JSON.parse(xmlhttp.responseText);
document.getElementById("txtphone").value = response.phone;
document.getElementById("txtpic").value = response.pic_name;
document.getElementById("txtaddress").value = response.address;

The above is from memory and not tested, but it should work.

Note: for compatibility with IE6 and 7, you’d need to include json2.js to parse the JSON.

My brother,

this is what I have been doing. I have explained in my responses above that this method works for me when I am reading the data unto <Select> </Select> combo boxes.
But when I read the data to text boxes, it does not work.

What I expect to hear from you is any tangible reasons why it works on one and does not work on the other.

Thank you for your magnanimous suggestions.
I will be appreciate more.
Thank you once again.

I’ve already explained why the code doesn’t work with your text inputs. Without seeing the JS for the loadParish function, it’s difficult to explain why that function works.

You know, I cannot just believe that it is difficult to explain why it does not work that way…
There should be something that I am skipping or misunderstanding.
I will definitely get to know it.
Let me continue find materials on AJAX in w3schools.com.
Although, they do not give comprehensive information about AJAX as a whole and everything that it entails.

Meanwhile, thanks all the same. But I can’t accept your explanation and your suggestion.
I’d continue searching information.
Thank you.

But if you have other helpful suggestions, you could still post them, you know?
Thanks.

As I said, if you post the JS for the loadParish function, I’ll be able to give you an explanation.

Is there something you don’t understand about my explanation? I’m happy to go into more detail if you have questions

I had posted the js script… It is embedded inside the .php file.
Thank you.