Question

I am developing a live search system using Ajax and PHP and it is working well. Although, I have one problem before I can say it is working as it should. I have multiple text fields and then you enter information the list updates. But, the list will start updating only if something has been entered into each field. Is there a way to fix this? I do want to add more fields as soon as this gets working though.

The Ajax:

<script type="text/javascript">
function showHint(keyword, city, state) {
    var xmlhttp;
    if(keyword.length == 0 & city.length == 0 & state.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
    }
    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("txtHint").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", "gethint.php?keyword=" + keyword + "&city=" + city + "&state=" + state, true);
    xmlhttp.send();
}
</script>

The HTML Form:

<form action="" id="livesearch" id="livesearch"> 
Clinic Name: <input type="text" id="clinicsearch" name="clinicsearch" autocomplete="off" onkeyup="keyword=this.value; showHint(keyword, city, state);" />
City: <input type="text" id="citysearch" name="citysearch" autocomplete="off" onkeyup="city=this.value; showHint(keyword, city, state);" />
State: <input type="text" id="statesearch" name="statesearch" autocomplete="off" onkeyup="state=this.value; showHint(keyword, city, state);" />
</form>

The PHP Script:

<?php
//get the parameters from URL
$keyword = $_GET['keyword'];
$city = $_GET['city'];
$state = $_GET['state'];
$query = mysql_query("SELECT * FROM users WHERE ClinicName LIKE '%$keyword%' AND LocationCity LIKE '%$city%' AND LocationRegion LIKE '%$state%'") or die(mysql_error());

if($query){//If query successfull
    if(mysql_affected_rows()!=0){//and if atleast one record is found
        while($rows = mysql_fetch_array($query)){ //Display the record
            $replace = str_replace(" ", "-", $rows['ClinicName']);
            echo '<p>'.$rows['UserID'] .' - <a href="clinic.php?clinicname='.$replace.'">'.$rows['ClinicName'].'</a> - '.$rows['Phone1'].'-'.$rows['Phone2'].'-'.$rows['Phone3'].' - '.$rows['LocationCity'].', '.$rows['LocationRegion'].' '.$rows['LocationZip'].', '.$rows['LocationCountry'].'</p>';
        }
    }
    else {
        echo 'No Results for:<br />Clinic Name: '.$keyword.'<br />City: '.$city.'<br />State: '.$state.'';//No Match found in the Database
    }
}
else {
    echo 'Parameter Missing in the URL';//If URL is invalid
}
?>
Was it helpful?

Solution

There is my solution for you:

just add following lines like that:

<script type="text/javascript">

var keyword = ''; // add this!
var city = ''; // add this!
var state = ''; // add this!

function showHint(keyword, city, state) {
// etc.

Happy coding!

OTHER TIPS

You should consider building your query dynamically to account for the fields you have available. Below is some code that I'm just typing out as a concept. I've not tested it and can't guarantee it's perfect.

<?php

   // Get the parameters from URL
   $params['keyword'] = $_GET['keyword'];
   $params['city'] = $_GET['city'];
   $params['state'] = $_GET['state'];

   // Start building query
   $sql = "SELECT * FROM users WHERE ";       

   // Loop through GET params and create WHERE clause
   foreach($params as $key=>$value)
   {
      // Only add to query if parameter not empty
      if( !empty(trim($value)) )
      {
         // Add to an array to be joined later using "AND"
         switch ($key) {
            case 'keyword':
               $whereCond[] = "ClinicName LIKE '%$value%'";
               break;
            case 'city':
               $whereCond[] = "LocationCity LIKE '%$value%'";
               break;
            case 'state':
               $whereCond[] = "LocationRegion LIKE '%$value%'";
               break;
         }
      }
   }

   // With where conditions, use a counter so 
   // we dont add "AND" to last one
   $iCount = 0;
   $iTotal = count($whereCond);  

   // Combine WHERE clause and add to query
   foreach($whereCond as $cond)
   {
      if($iCount != $iTotal)
      {
         $sql .= $cond . " AND ";
      } else {
         $sql .= $cond;
      }

      // Increment counter
      $iCount++;
   }

   // Run query
   $query = mysql_query($sql) or die(mysql_error());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top