AJAX suggest

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
bimo
Forum Contributor
Posts: 100
Joined: Fri Apr 16, 2004 11:18 pm
Location: MD

AJAX suggest

Post by bimo »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I'm trying to use an autocomplete script from the book [u]AJAX and PHP[/u].  I've worked through some of the errors and I thought I had configured it correctly but am receiving the error, "xmlHttpGetSuggestions.responseXML has no properties."  Here's the javascript xmlHttpGetSuggestion function (also, xmlHttpGetSuggestions is the XMLHttpRequest instance and contains the mysql db connection):
[syntax="javascript"]/* initiate HTTP request to retrieve suggestions for the current keyword */
function getSuggestions(keyword) 
{  
  /* continue if keyword isn't null and the last pressed key wasn't up or 
     down */
  if(keyword != "" && !isKeyUpDownPressed)
  {
    // check to see if the keyword is in the cache
    isInCache = checkCache(keyword);
    // if keyword is in cache...
    if(isInCache == true)          
    {   
      // retrieve the results from the cache          
      httpRequestKeyword=keyword;
      userKeyword=keyword;     
      // display the results in the cache
      displayResults(keyword, oCache[keyword]);                          
    }
    // if the keyword isn't in cache, make an HTTP request
    else    
    {    
      if(xmlHttpGetSuggestions)
      { 
        try
        {
          /* if the XMLHttpRequest object isn't busy with a previous
             request... */
          if (xmlHttpGetSuggestions.readyState == 4 || 
              xmlHttpGetSuggestions.readyState == 0) 
          {    
            httpRequestKeyword = keyword;
            userKeyword = keyword;
            xmlHttpGetSuggestions.open("GET", 
                                getFunctionsUrl + encode(keyword), true);
            xmlHttpGetSuggestions.onreadystatechange = 
                                                handleGettingSuggestions; 
            xmlHttpGetSuggestions.send(null);
          }
          // if the XMLHttpRequest object is busy...
          else
          {
            // retain the keyword the user wanted             
            userKeyword = keyword;
            // clear any previous timeouts already set
            if(timeoutId != -1)
              clearTimeout(timeoutId);          
            // try again in 0.5 seconds     
            timeoutId = setTimeout("getSuggestions(userKeyword);", 500);
          }
        }
        catch(e)
 
        {
          displayError("Can't connect to server:\n" + e.toString());
        }
      }
    }    
  }
}
and heres the php function GetSuggestions:[/syntax]

Code: Select all

// returns all PHP functions that start with $keyword
  public function getSuggestions($keyword)
  {
    // escape the keyword string      
    $patterns = array('/\s+/', '/"+/', '/%+/');
    $replace = array('');
    $keyword = preg_replace($patterns, $replace, $keyword);
    // build the SQL query that gets the matching functions from the database
    if($keyword != '')
      $query = 'SELECT name ' .
               'FROM suggest ' . 
               'WHERE name LIKE "' . $keyword . '%"';
    // if the keyword is empty build a SQL query that will return no results
    else
      $query = 'SELECT name ' .
               'FROM suggest ' .
               'WHERE name=""'; 
    // execute the SQL query
    $result = $this->mMysqli->query($query);
    // build the XML response
    $output = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
    $output .= '<response>';    
    // if we have results, loop through them and add them to the output
    if($result->num_rows)
      while ($row = $result->fetch_array(MYSQLI_ASSOC)) 
        $output .= '<name>' . $row['name'] . '</name>';
    // close the result stream 
    $result->close();
    // add the final closing tag
    $output .= '</response>';   
    // return the results
    return $output;  
  }
Can anyone think why it would be giving me this error?

thanks,

-b


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
kendall
Forum Regular
Posts: 852
Joined: Tue Jul 30, 2002 10:21 am
Location: Trinidad, West Indies
Contact:

Post by kendall »

bimo,

It could be because you are getting responseText rather than responseXML. I take it you arent getting any errors? I'm not user but either set the content header in the php file to text/xml or u may want to make a XML Object out of the responseText
User avatar
bimo
Forum Contributor
Posts: 100
Joined: Fri Apr 16, 2004 11:18 pm
Location: MD

Post by bimo »

Kendal, I thought it was creating an xml object but maybe it isn't working. Here's the code:

Code: Select all

<?php
// load error handling module
require_once('error_handler.php');
// load configuration file
require_once('config.php');

// class supports server-side suggest & autocomplete functionality
class Suggest
{
	// database handler
	private $mMysqli;
	
	// constructor opens database connection
	function __construct()
	{
		// connect to the db
		$this->mMysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
	}
	
	// destructor, closes database connection
	function __desturct()
	{
		$this->mMysqli->close();
	}
	
	// returns all artists that start with $keyword
	public function getSuggestions($keyword)
	{
		// escape the keyword string
		$patterns = array('/\s+/', '/"+/', '/%+/');
		$replace = array('');
		$keyword = preg_replace($patterns, $replace, $keyword);
		// build the sql query that gets the matching functions from the database
		if($keyword != '')
			$query = 'select 
						artist 
					  from 
					  	recordings
					  where
					  	artist like "' . $keyword . '%"';
		// if the keyword is empty, build a SQL query that will return no results
		else
			$query = 'select
						artist
					  from 
					  	recordings
					  where 
					  	artist=""';
		// execute the SQL query
		$result = $this->mMysqli->query($query);
		// build the xml respose
		$output = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
		$output .= '<response>';
		// if we have results, loop through them and add them to the output
		if($result->num_rows)
			while ($row = $result->fetch_array(MYSQLI_ASSOC))
				$output .='<name>' . $row['artist'] . '</name>';
		// close the result stream
		$result->close();
		// add the final closing tag
		$output .= '</response>';
		// return the results
		return $output;
	}
//end class suggest
}
?>
how can I tell if it's writing the xml correctly? I've checked the query and it works.

Thanks
User avatar
kendall
Forum Regular
Posts: 852
Joined: Tue Jul 30, 2002 10:21 am
Location: Trinidad, West Indies
Contact:

Post by kendall »

bimo,

Well it may be creating "XML tags" and it may be well formed as well but when its "returned" to the xmlHttpGetSuggestions its being returned in "string" and not XML Object thus its a "STRING" of xml tags

You need to google around there was a script that i had taken from a tutorial that takes the xmlHttpGetSuggestions.responseText and created an XML object out of it.
User avatar
bimo
Forum Contributor
Posts: 100
Joined: Fri Apr 16, 2004 11:18 pm
Location: MD

Post by bimo »

Nice...

thanks, kendall

-b
Post Reply