Jump to content

Livesearch tut at w3schools-http://www.w3schools.com/php/php_ajax_livesearch.asp


baseballfury

Recommended Posts

Hello there,

I'm extremely new to AJAX so please bear with me. I'm working through a w3schools exampe which makes use of an xml form to create a google type 'suggestion' search bar. The code seems ok if albeit a bit messy (or crap as a fellow forum member used on a similar topic) as when i type something into the bar it comes up with "no suggestion" which is not the final goal but at least i shows th code is doing something. Unfortunately thats all i can get it to do. I copied the javascipt code and saved it but whenever i view it there appears to be an issue with the quotes and double quotes within the code i.e. online it looks like this:

 

if (str.length==0)

{

document.getElementById("livesearch").

innerHTML="";

document.getElementById("livesearch").

style.border="0px";

return

}

 

whereas mine looks like this: (not the complete code obviously)

 

if (str.length==0)

{

document.getElementById("livesearch').

innerHTML="';

document.getElementById("livesearch').

style.border="0px';

return

}

 

I don't think this is a part of my problem but was wondering why the quotes change when viewed in Dreamweaver.

 

Anywho i'm at sea a bit with this code but from what i can tell from the javascript sends a url to the PHP file so when the user clicks the "suggestion" they navigate to a page. Obviously i have an xml file with a number of 'title' and 'url' saved in it

but i don't actually have these url's on my webspace because they are w3schools' url's. Do i need to change the details of the xml file to match the files on my webspace for it to work. I'll attach all the code from the example below.

 

I really appreciate any time you could give this matter and if this post shows my complete ineptitude then my apologies.

 

//the javascript

var xmlHttp

function showResult(str)

{

if (str.length==0)

{

document.getElementById("livesearch").

innerHTML="";

document.getElementById("livesearch").

style.border="0px";

return

}

xmlHttp=GetXmlHttpObject()

if (xmlHttp==null)

{

alert ("Browser does not support HTTP Request")

return

}

var url="livesearch.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 || xmlHttp.readyState=="complete")

{

document.getElementById("livesearch").

innerHTML=xmlHttp.responseText;

document.getElementById("livesearch").

style.border="1px solid #A5ACB2";

}

}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;

}

 

//the PHP

<?php

$xmlDoc = new DOMDocument();

$xmlDoc->load("links.xml");

$x=$xmlDoc->getElementsByTagName('link');

//get the q parameter from URL

$q=$_GET["q"];

//lookup all links from the xml file if length of q>0

if (strlen($q) > 0)

{

$hint="";

for($i=0; $i<($x->length); $i++)

{

$y=$x->item($i)->getElementsByTagName('title');

$z=$x->item($i)->getElementsByTagName('url');

if ($y->item(0)->nodeType==1)

  {

  //find a link matching the search text

  if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))

  {

  if ($hint=="")

    {

    $hint="<a href='" .

    $z->item(0)->childNodes->item(0)->nodeValue .

    "' target='_blank'>" .

    $y->item(0)->childNodes->item(0)->nodeValue . "</a>";

    }

  else

    {

    $hint=$hint . "<br /><a href='" .

    $z->item(0)->childNodes->item(0)->nodeValue .

    "' target='_blank'>" .

    $y->item(0)->childNodes->item(0)->nodeValue . "</a>";

    }

  }

  }

}

}// Set output to "no suggestion" if no hint were found

// or to the correct values

if ($hint == "")

{

$response="no suggestion";

}

else

{

$response=$hint;

}//output the response

echo $response;

?>

 

//the xml document - in part

<?xml version="1.0" encoding="ISO-8859-1" ?>

- <!--  Edited by XMLSpy®

  -->

- <pages>

- <link>

  <title>HTML DOM alt Property</title>

  <url>http://www.w3schools.com/htmldom/prop_img_alt.asp</url>

  </link>

  </pages>

 

Thanks again

Link to comment
Share on other sites

Using PHP 5.x

 

livesearch.html

<html>
<head>
<script src="livesearch.js"></script> 
<style type="text/css"> 
#livesearch{ 
  margin:0px;
  width:194px; 
}
#txt1{ 
  margin:0px;
} 
</style>
</head>
<body>

<form>
<input type="text" id="txt1" size="30" onkeyup="showResult(this.value)">

<div id="livesearch"></div>
</form>

</body>
</html>

 

livesearch.js

//--------------------------------------------
//  XMLHttpRequestObject:
//    How we request data from the server.
//--------------------------------------------
function getXHRO()
{
  try { return new XMLHttpRequest(); } catch(e) {}//Firefox,Safari,Opera
  try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}//Newer IE
  try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}//Older IE
  alert("XMLHttpRequest not supported");
  return null;
}
//-------------------------------------------------------------------------------

//if there isn't anything in the box, hide the results
function showResult(str){
  if (str.length==0){ 
    document.getElementById("livesearch").innerHTML="";
    document.getElementById("livesearch").style.border="0px";
      return;
  }
  //all good, pass the current input text to our search function
  liveSearch(str);
}


//the search function
//receives input string from previous function,
//appends the $_GET request to the url (ex: http://page.com/index.php?q=str)
//appends a random number so we don't get cached results
//sends data request
//receives data, traverses XML
//places results on screen
function liveSearch(str){
  var XHRO = new getXHRO();
  //if we cannot create an XMLHttpRequestObject, no point continuing
  if(XHRO == null){ alert('Your browser doesn\'t support Ajax.');return false;}
  
  var url = "livesearch.php";//url to send to
    url += "?q=" + str;//append query to url
    url += "&sid=" + Math.random();//append random numbers to eliminate cache

  XHRO.onreadystatechange = function(){//a function to handle the response
    if (XHRO.readyState==4 || XHRO.readyState=="complete"){ 
      document.getElementById("livesearch").innerHTML=XHRO.responseText;
      document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
  }
  XHRO.open("GET",url,true);//start the connection
  XHRO.send(null);// "send" nothing (you post parameters here when using POST)

}//liveSearch

//used to handle the responseText
function showResults(){

}

 

livesearch.php

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("livesearch.xml");

$x=$xmlDoc->getElementsByTagName('link');

//get the q parameter from URL
$q=$_GET["q"];

//lookup all links from the xml file if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
{
$y=$x->item($i)->getElementsByTagName('title');
$z=$x->item($i)->getElementsByTagName('url');
if ($y->item(0)->nodeType==1)
  {
  //find a link matching the search text
  if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
   {
   if ($hint=="")
    {
    $hint="<a href='" . 
    $z->item(0)->childNodes->item(0)->nodeValue . 
    "' target='_blank'>" . 
    $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
    }
   else
    {
    $hint=$hint . "<br /><a href='" . 
    $z->item(0)->childNodes->item(0)->nodeValue . 
    "' target='_blank'>" . 
    $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
    }
   }
  }
}
}

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}

//output the response
echo $response;
?>

 

livesearch.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<pages>
<link>
<title>HTML DOM alt Property</title>
<url>http://www.w3schools.com/htmldom/prop_img_alt.asp</url>
</link>
<link>
<title>HTML DOM height Property</title>
<url>http://www.w3schools.com/htmldom/prop_img_height.asp</url>
</link>
<link>
<title>HTML a tag</title>
<url>http://www.w3schools.com/tags/tag_a.asp</url>
</link>
<link>
<title>HTML br tag</title>
<url>http://www.w3schools.com/tags/tag_br.asp</url>
</link>
<link>
<title>CSS background Property</title>
<url>http://www.w3schools.com/css/pr_background.asp</url>
</link>
<link>
<title>CSS border Property</title>
<url>http://www.w3schools.com/css/pr_border.asp</url>
</link>
<link>
<title>JavaScript Date() Method</title>
<url>http://www.w3schools.com/jsref/jsref_date.asp</url>
</link>
<link>
<title>JavaScript anchor() Method</title>
<url>http://www.w3schools.com/jsref/jsref_anchor.asp</url>
</link>
</pages>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.