Php search technique and automatic posting to textboxes

i have a form that contains some text boxes lets say address,area,group of districts,region and i also have a database that contains the details of each…like my area table contains id,name,group_of_district_id,region_id… my region table has id and name likewise my group_of_district table too. so they are foreign keys in the area table i want to make it work in such a way that if i enter my area in the space available via the interface,d group_of_district and region related to it pops out the table image when i fill in the area,and the area is found in the database,the region and group_of_district related to it should save in the space provided for them

I’d think you would want a quick Ajax call to a short PHP routine that retrieves the region and so on from your database and populates the required fields.

What PHP and Ajax experience do you have? This is a very common usage for Ajax, and indeed was my own starting point (and ending point, so far) to just have form fields automatically filled in, so a basic tutorial on Ajax would probably help you.

Does your form really need to be a form with multiple fields? That is, once your user has entered an area that is in your database, do you really need them to be able to edit the region and group_of_district fields? If not, it’s poor UI design (in my opinion) to put them as form text boxes as that will suggest to the user that they can edit the information. And if they do edit it, how are you going to deal with the information changing?

So if editing isn’t allowed, just display the information. You can still use Ajax to do it without having to have a page submit, unless the user disables JavaScript. And if the area fields is something that should be validated against a database table, wouldn’t it be better as an option select rather than a text box, so users can just choose one from the list?

if the area is entered,and then its found in the database,it shouldnt be editable but if the area entered is not found,the user should be allowed to enter the region and group_of_district.i ve got no idea of AJAX at all

OK, well have a look for an Ajax tutorial, odds on that one of the first interactive things they teach will be how to do a quick lookup for populate form fields.

As an example, here’s a bit of sanitised code from the basic stuff I did.

This is the form itself, which is echoed because it’s output from a main php page. It’s a database to store a list of what cars are featured in which issues of a magazine:

echo '<form method="post" action=""><input type="hidden" name="issue" value="' . $issuenum . '">';
echo '<table><tr><td>Registration No. </td><td><input type="text" name="registration" maxlength="8" size="8" id="reg" onblur="findReg()"></td></tr>';
echo '<tr><td>Vehicle Model</td><td><input type="text" name="model" size="30" maxlength="30" id="carmodel"></td></tr>';
echo '<tr><td>Type of entry (ad, article, etc.)</td><td><input type="text" name="type" size="10" maxlength="10"></td></tr>';
echo '<tr><td>Notes</td><td><input type="text" name="note" maxlength="30" size="30"></td></tr>';
echo '<tr><td><input type="submit" name="addvehicle" value="Add Vehicle"></td><td>&nbsp;</td></tr></table></form>';

Included in the top of the page I have a reference to the JavaScript, which is

var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject()
{
  var xmlHttp;
  if(window.ActiveXObject)
  { 
    try
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    catch (e)
    {
      xmlHttp = false;
    }
  }
  else
  {
    try
    {
      xmlHttp = new XMLHttpRequest();
    }
    catch (e)
    {   
      xmlHttp = false;
    }
  }
  if (!xmlHttp)
    alert("Error creating the XHR Object.");
  else
    return xmlHttp;
}

function findReg()
{
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {
    name = encodeURIComponent(document.getElementById("reg").value);
    xmlHttp.open("GET", "reglook.php?reg=" + name, true);
    xmlHttp.onreadystatechange = handleServerResponse;
    xmlHttp.send(null);
    }
  else
  {
    setTimeout('findReg()', 1000);
  }
}

function handleServerResponse()
{
  if (xmlHttp.readyState == 4)
  {
    if (xmlHttp.status == 200)
    {
      xmlResponse = xmlHttp.responseXML;
      xmlDocumentElement = xmlResponse.documentElement;
      dataReturned = xmlDocumentElement.firstChild.data;
      if (dataReturned == "Not Found") { 
        document.getElementById('carmodel').value = "";
        }
      else {
        document.getElementById('carmodel').value = dataReturned;
        }
      }
    else
    {
      alert("Problem accessing server " + xmlHttp.statusText);
    }
  }
}

And the PHP code to do the actual lookup is

<?php

require_once("../magissues_db.php");

header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$reg = strtoupper(StripReg($_GET['reg'])); // added toupper() although stripreg should already do it.

$q = "select vehicle_type from vehicles where vehicle_reg = :r";
$b = $dbc->prepare($q);
$b->bindParam(':r', $reg);
$b->execute();

if ($row = $b->fetch()) { 
  echo $row['vehicle_type'];
  }
else
  {
  echo 'Not Found';
  }
echo '</response>';
?>

So you can see that in the form, I have an onBlur() call which calls my JavaScript code whenever the focus leaves the text box, i.e. when the user has typed in the registration number in my example.

The meat of the JavaScript is in the FindReg() function, the remainder of it is the same regardless of what the code is actually doing. That function gets the contents of the form field and calls the PHP code. If it gets a response of “Not found” it does nothing, otherwise it sticks the returned string into the appropriate form field.

The PHP to actually do the lookup is straightforward, it just strips out spaces and converts to upper case. In fact the StripReg() function coverts to upper case as well, but I’ve had issues with it not returning a result even though the registration is in the database so I added another conversion to upper case in case that helped. It didn’t.

There is also jQuery to look at, which I believe removes the need for some of my code and might make things easier. But, but, but, I have this working so I’ve left it alone. No doubt someone will be along to show how it could be done in a couple of lines using jQuery.

What you need to do is adapt the code to do your lookup, and fill out the form fields if you get a result. If you’re not going to allow the user to edit fields that are found in the database, the success code could probably disable the form fields if it fills them in, or leave them active if it does not.

thanks so much…would just read about it and go through this for better understanding

hi everyone…After using ajax and php for posting to textboxes after selecting an option in a dropdown
let me break it down
my register.php page

Residential Area:
  <select name="area" onchange="showUser(this.value)" id="area" value=""/>
    <option value="Area">Select an area<br></option>

<?php
  $query_area="SELECT * FROM area";

  $result_area=mysqli_query($db,$query_area ); 
  
  while ($resource_area=mysqli_fetch_array($result_area)) {
    echo "<option value=\"{$resource_area['id']}\">{$resource_area['name']}</option>";
    $resource_area++;
    }
    
    ?>
  </select>
  <br>
  <br>
  <div id="txtHint"><b>The group of district and region of residence will be shown here...</b></div>
 
  <br>

my header.php page where i have the ajax script

 <script>
  function showUser(str) {
    if (str=="") {
      document.getElementById("txtHint").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 (this.readyState==4 && this.status==200) {
        document.getElementById("txtHint").innerHTML=this.responseText;
      }
    }
    
    xmlhttp.open("GET","getuser.php?q="+str,true);
    xmlhttp.send();
  }
</script>

and my getuser.php where i av my query

?php
require_once("../includes/config.php");


$area_id = $_GET['q'];


$sql = "SELECT area.id,group_of_districts.name,region.name AS reg_name FROM area 
		JOIN group_of_districts ON group_of_districts.id = area.group_of_district_id
		JOIN region ON region.id = area.region_id
		WHERE area.id = '".$area_id."'";

$result = mysqli_query($db,$sql);
while($row = mysqli_fetch_array($result)) {
	?>
  <input type="text" name="group_of_district" id="group_of_district" value="<?php echo $row['name'];?>" readonly="readonly">
  <br>
  Region:
  <input type="text" name="region" id="region" value="<?php echo $row['reg_name'];?>" readonly="readonly"/> 
  <?php

}



?>

but when i go to d browser and i dont fill the form,i get the message undefined index for the two textboxes
but i fill the form till d point of selecting the area,i get error messages for the ones i validated

I don’t understand why you’ve got text boxes in the PHP code that your Ajax calls. That’s a small bit of code called from your main code in register.php, and the output doesn’t appear anywhere. The output is returned to the main code in responseText, and your JS code sticks it into the appropriate DIV in the main page. So at best, your input text boxes won’t appear anywhere.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.