Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help with updating search results

Status
Not open for further replies.

coolicus

Programmer
May 15, 2007
50
GB
I have done some html but am new to this scripting lark, anyway I have managed to create a mySQL database and a php web page to search the database and bring the results

I would like to filter the results, the user simply types a region to start with say UK, then onn the results page are all of the results in UK, at the top of the page are checkboxes;

show only results that are
option 1 [checkbox] option 2 [checkbox] etc

someone told me I should use ajax to automatically update the results if they tick one of the boxes. Can someone point me in the right direction here, I am not afraid to :)
 
the process is:

set an onchange event to select box 1 that sends the value to your php script.
in your php script take the incoming variable and work out what options should be in select2. format the options in html. send them back (echo them)
in your ajax script capture the responsetext and insert it as the innerhtml of select2.

i.e. it's really simple. if you don't have a select 1 then use a text box. play around with whether onchange is better than onblur. you may want to apply your test on onkeydown but if so i'd recommend you insert a delay (of say a second) so that you avoid the back/forth traffic
 
Can you point me in the direction of a tutorial that I can look at that doesn`t assume prior knowledge? All the ajax sites I have looked at assume I know lots of javascript
 
this is not the place to 'learn' a language, as you've probably guessed.

w3schools is a good place to learn javascript.

as for ajax sites assuming you know lots of javascript: this is not surprising given that js is the fundamental part of ajax!

here's a brief tutorial however:

1. we need an html file and a php file. the php file will manage the interaction from the js in the html file.

2. let's assume some data. let's say a bunch of countries: France, Spain, Great Britain, and a bunch of cities within those countries. selecting a country causes a secondary drop down to appear.

so the php and html files look like this

Code:
<?php
/**
 *	ajaxserver.php
 */
 
 //establish some dummy data
 $countries = array('Great Britain', 'France', 'Spain');
 $cities = array(	'Great Britain'=>
 					array(	'London',
							'Manchester',
							'Birmingham',
							'Leeds',
							'Bath',
							'Bristol'
						),
					'France'=>
					array(	'Paris',
							'Toulouse',
							'Lyon',
							'Marseille',
							'Bordeaux'
						),
					'Spain'=>
					array(	'Madrid',
							'Toledo',
							'Granada',
							'Malaga',
							'Barcelona'
						)
				);

//start the motor
switchboard();

function switchboard(){
 	$action = isset($_POST['action']) ? trim($_POST['action']) : '';
	$permittedActions = array('getCityOptions');
	//validate the requested option
	if (!in_array($action, $permittedActions)){
		sendOutput('');
	}
	
	switch ($action){
		case 'getCityOptions':
			$options = getCityOptions();
			sendOutput($options);
		break;
		//use this to add other actions in
	}
}
/**
 * this function sends output to the calling page.
 * we use some no cache headers to prevent the browser from caching results.
 * it should not do this using POST vars but you never know
 */
function sendOutput($output){
	header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
	echo $output;
	//always exit or die at the end of an ajax call
	exit();
}

function getCityOptions(){
	global $countries, $cities;
	//grab the country requests
	$country = isset($_POST['country']) ? trim ($_POST['country']) : '';
	//validate that the country is a permitted country
	if (!in_array($country, $countries)){
		sendOutput('');
	}
	//we know we have a valid country
	//grab the cities
	$cities = $cities[$country];
	//format as options
	$options = compileOptions($cities);
	//return the options to the calling function
	return $options;
}
 
/**
 * this function just takes an array and makes it into a string of options
 * suitable for use in a select box
 */
function compileOptions($array){
 	$output = '';
	foreach ($array as $value){
		$output .= <<<HTML
	<option value="$value">$value</option>

HTML;
	}
	return $output;
}
?>

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Ajax Test</title>
<script language="javascript" type="text/javascript">
var xo = false;
var url = 'ajaxserver.php';
function getCities(val){
	var params = 'action=getCityOptions&country=' + encodeURI(val);
	xo = false;
	if (!xo){
		xo = makeObject();
	}
	
	xo.onreadystatechange=fillCities;
	xo.open('POST', url, true);
	xo.setRequestHeader("Content-type", "application/x-[URL unfurl="true"]www-form-urlencoded");[/URL]
	xo.setRequestHeader("Content-length", params.length);
	xo.setRequestHeader("Connection", "close");
	xo.send(params);
}
function makeObject(){
	var xmlhttp;
	if (window.XMLHttpRequest){
  		xmlhttp=new XMLHttpRequest();
  	}else if (window.ActiveXObject){
  		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  	}
	return xmlhttp;
}

function fillCities(){
	if (xo.readyState == 4) {
         if (xo.status == 200) {
			var elem = document.getElementById('cities');
			if (xo.responseText.length > 0){
				elem.innerHTML = xo.responseText;
			}
		}
	}
}
//fire the process up once the page is loaded, to fill in the second select box
window.onload = function(){
				getCities(document.getElementById('countries').value);
				}
</script>
</head>

<body>

<div>
<select name="countries" id="countries" onchange="getCities(this.value);">
	<option value="Great Britain">Great Britain</option>
	<option value="France">France</option>
	<option value="Spain">Spain</option>
</select>
</div>
<div>
<select name="cities" id="cities">
</select>
</div>
</body>
</html>
 
I am getting there :)

I can update the search results but the paging isn`t updating, as the results goes from many to two, the paging still says 'next results'

I created a div called newresults and this where the original results are, then they are over written by the ajax results. I then extended the div to cover the paging and placed the paging into my ajax results php script but it ignoresd the paging?!?!

searchresults.php
Code:
<div class="container"> 
  <div class="header"></div> 
  
  <div class="main_area"> 
    <div class="content"> <img src="images/tit_results.jpg" alt="Search results..." width="164" height="19" /> 
				


<?php
require "dbconn.php";

//grab the number of results for the field below
$query2  = "SELECT COUNT(*) as c FROM properties where city LIKE '%".
mysql_real_escape_string($_GET[city])."%'";
$result2 = mysql_query($query2) or die (mysql_error());
$numRows = mysql_result($result2, 0, 0);

?>

      <p class="MainText">We found<span class="BlueText"> <?php echo $numRows['c'] ?> </span> properties matching your search terms. To narrow your results please use the options below, or view all of the results as they are. </p> 




      <div class="narrow_results"><span class="BlueText">Please only include properties that have/are... </span> 
        <form> 
          <table width="100%"  border="0" cellspacing="0" cellpadding="0" class="MainText"> 
            <tr> 
              <td><input type="checkbox" name="pool" value="1" onchange="updateResults(this.value)" /> 
                Swimming Pool</td> 
              <td><input type="checkbox" name="seaview" value="1" onchange="updateResults(this.value)" /> 
                Sea Views </td> 
              <td><input type="checkbox" name="lift" value="1" onchange="updateResults(this.value)" /> 
                Shabbat Lift </td> 
              <td><input type="checkbox" name="disabled" value="1" onchange="updateResults(this.value)" /> 
                Disabled Facilities </td> 
            </tr> 
            <tr> 
              <td><input type="checkbox" name="parking" value="1" onchange="updateResults(this.value)" /> 
                Underground Parking </td>            
              <td><input type="checkbox" name="terrace" value="1" onchange="updateResults(this.value)" /> 
                Sun Terrace </td> 
              <td><input type="checkbox" name="aircon" value="1" onchange="updateResults(this.value)" /> 
                Central Air Conditioning </td> 
														<td>&nbsp;</td>
            </tr> 
          </table> 
        </form> 
      </div>


<script src="ajaxupdate.js"></script>
<DIV ID='newresults'>

<?php

//paging
$page_name="search_results.php";
$start=$_GET['start'];
if(!($start > 0)) { 
$start = 0;
}
$eu = ($start - 0); 

if(!$limit > 0 ){ // if limit value is not available then let us use a default value
$limit = 4;    // No of records to be shown per page by default.
}                             
$this1 = $eu + $limit; 
$back = $eu - $limit; 
$next = $eu + $limit;


$query=" SELECT * FROM properties where city LIKE '%{$_GET[city]}%' limit $eu, $limit ";
$result=mysql_query($query);
echo mysql_error();


while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
				if($style=='search_result_even'){$style='search_result_odd';}
    else{$style='search_result_even';}
    echo "<div class='$style'><span class='BlueText'><img src='images/result_1.jpg' alt='{$row['name']}' width='150' height='150' class='result_small' />{$row['name']}, {$row['address']} - <strong>&pound;{$row['price']}</strong></span>" .
         "<p class='MainText'>{$row['maindesc']} <span class='BlueText'>Property ID {$row['id']}.</span></p>" .
         "<p class='MainText'><a href='property.php?id={$row['id']}' class='BlueText'>More Information....</a> | <a href='#' class='BlueText'>Enquire Now!</a> </p>" .
									"</div>";
}

?> 
				



    </div> 

				
<?php
//display previous if there are previous
if($back >=0) { 
print "<span class='BlueText'><strong>< <a href='$page_name?start=$back&limit=$limit&city=$_GET[city]'>Previous properties</a></strong></span> | "; 
} 

//display page numbers
$i=0;
$l=1;
for($i=0;$i < $numRows;$i=$i+$limit){
if($i <> $eu){
echo " <a href='$page_name?start=$i&limit=$limit'>$l</a> ";
}
else { echo "<span class='MainText'><b>$l</b></span>";}        
$l=$l+1;
}

//display next if there are next
if($this1 < $numRows) { 
print "| <span class='BlueText'><strong><a href='$page_name?start=$next&limit=$limit&city=$_GET[city]'>Next properties</a> ></strong></span>";} 



?>
				
<!--end new results div for the ajax results update scripts-->				
</DIV>		
				
				</span></div> 
  </div> 
  <div class="footer"> 
    <div class="footer_right"> 
      <div class="newsletter"> 
        <form id="form2" method="post" action=""> 
          <input name="textfield2" type="text" class="newsletter_input_box" value="Email address..." /> 
          <input name="Submit2" type="submit" class="newsletter_button" value="Send" /> 
        </form> 
      </div> 
      <span class="BlueText">Newsletter</span><span class="WhiteText">, rutrum at, eros.<br /> 
      Quisque vita prae sent lect, vestibulum.</span> </div> 
    <img src="images/footer_quote.jpg" alt="Theisraelpropertyshop.com" width="493" height="130" /></div> 
</div>

ajaxupdate.js
Code:
var xmlHttp

function updateResults(str)
{ 
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  } 
var url="ajax_results.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged()
{ 
if (xmlHttp.readyState==4)
{ 
document.getElementById("newresults").innerHTML=xmlHttp.responseText;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

ajaxresults.php
Code:
<?php
$q=$_GET["q"];

require "dbconn.php";



//paging
$page_name="search_results.php";
$start=$_GET['start'];
if(!($start > 0)) { 
$start = 0;
}
$eu = ($start - 0); 

if(!$limit > 0 ){ // if limit value is not available then let us use a default value
$limit = 4;    // No of records to be shown per page by default.
}                             
$this1 = $eu + $limit; 
$back = $eu - $limit; 
$next = $eu + $limit;







$sqlupdate="SELECT * FROM properties WHERE pool = '".$q."' AND city LIKE '%{$_GET[city]}%' limit $eu, $limit";

$resultupdate = mysql_query($sqlupdate);


while($rowupdate = mysql_fetch_array($resultupdate, MYSQL_ASSOC))
 {
 if($style=='search_result_even'){$style='search_result_odd';}
    else{$style='search_result_even';}
    echo "<div class='$style'><span class='BlueText'><img src='images/result_1.jpg' alt='{$rowupdate['name']}' width='150' height='150' class='result_small' />{$rowupdate['name']}, {$rowupdate['address']} - <strong>&pound;{$rowupdate['price']}</strong></span>" .
         "<p class='MainText'>{$rowupdate['maindesc']} <span class='BlueText'>Property ID {$rowupdate['id']}.</span></p>" .
         "<p class='MainText'><a href='property.php?id={$rowupdate['id']}' class='BlueText'>More Information....</a> | <a href='#' class='BlueText'>Enquire Now!</a> </p>" .
									"</div>";
 }








//display previous if there are previous
if($back >=0) { 
print "<span class='BlueText'><strong>< <a href='$page_name?start=$back&limit=$limit&city=$_GET[city]'>Previous properties</a></strong></span> | "; 
} 

//display page numbers
$i=0;
$l=1;
for($i=0;$i < $numRows;$i=$i+$limit){
if($i <> $eu){
echo " <a href='$page_name?start=$i&limit=$limit'>$l</a> ";
}
else { echo "<span class='MainText'><b>$l</b></span>";}        
$l=$l+1;
}

//display next if there are next
if($this1 < $numRows) { 
print "| <span class='BlueText'><strong><a href='$page_name?start=$next&limit=$limit&city=$_GET[city]'>Next properties</a> ></strong></span>";} 






//mysql_close($con);
?>

gees my head is starting to spin!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top