I've searched through the questions here but haven't found a precise answer to my query :( However, I have managed to find something.
I have a form select field that I populate from a database query.
<select style="width:100%;" class="quform-tooltip chosen-select" id="company_select" name="company_select" title="Company Select" onChange="showUser(this.value)">
<option value="">Please select</option>
<?php
$userID = $user->getUserID();
$query = $user->database->query("SELECT * FROM tbl_businesses as business LEFT JOIN tbl_user_businesses as biz_user ON business.businessID = biz_user.businessID WHERE biz_user.userID ='$userID'");
while($row=$user->database->fetchArray($query))
{
$bizID = $row['businessID'];
$bizName = $row['businessName'];
echo "<option value='$bizID'>$bizName</option>";
}?>
</select>
Currently, there are 2 other textboxes (which may increase in the future) that I want to populate when the value of the select box above is changed/selected.
<input id="company_name" type="text" name="company_name" value="" />
<input id="company_email" type="text" name="company_email" value="" />
So, I have an onchange function on my select box which is this:
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("company_name").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)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("company_name").innerHTML += data[i].id + ' - ' + data[i].name + ' - ' + data[i].web;
}
}
}
xmlhttp.open("GET","formdata.php?q="+str,true);
xmlhttp.send();
}
</script>
And my formdata.php file is like this:
<?php
include("include/user.php");
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_businesses WHERE businessID = '".$q."'";
$result = $user->database->query($sql);
$info = array();
while($row=$user->database->fetchArray($result))
{
$cID = $row['bussinessID'];
$cName = $row['businessName'];
$cWeb = $row['businessWebsite'];
$info[] = array( 'id' => $cID, 'name' => $cName, 'web' => $cWeb );
}
echo json_encode($info);?>
The ajax call is functioning correctly and returning the expected data, but now I need help populating the textbox values.
Could someone please assist me with this? I've spent a lot of time trying to figure it out. I'm not familiar with JavaScript/JSON, so I don't know where to start.
I'd like the company_name textbox value to be set to $cName and the company_email textbox value to be set to $cWeb.
Appreciate any assistance.
Luke