Jump to content

Trobles with w3schools' "PHP and AJAX Live Search" tutorial..


Guest kilbad

Recommended Posts

I am having problems with w3schools' "PHP and AJAX Live Search" tutorial, found at [url=http://www.w3schools.com/php/php_ajax_livesearch.asp]http://www.w3schools.com/php/php_ajax_livesearch.asp[/url].  I am just starting to learn AJAX, and I was attempting to simply reproduce the example shown on my own server so I could experiment with it (see: [url=http://www.kilbad.com/DEVELOPMENT/livesearchFORM.php]http://www.kilbad.com/DEVELOPMENT/livesearchFORM.php[/url]).  All the files on the server have the same exact code as the example files.  However, I am getting the following error: "Parse error: syntax error, unexpected T_OBJECT_OPERATOR...on line 16."

Therefore, I was wondering if someone could help me sort out this problem.

Thank you all so much in advance!
Brendan
Link to comment
Share on other sites

To be brutally honest, that code is crap.. There are several things wrong with it. In the showResult function, the order that they had didn't make any sense. Lets look at this from a logical stand point. First you are going to open the file. Then you are going to send any thing that needs to be sent. In the case of "GET" you send null. Then when the readyState has changed send it to the next function for processing.



This should be a working version of the mess at w3schools, assuming there are not issues with the php.

[code=php:0]
//obers request object
function createRequestObject() {
    if (window.XMLHttpRequest) { // Mozilla, Safari, Opera...
        var xmlhttp = new XMLHttpRequest();
        if (xmlhttp.overrideMimeType)
xmlhttp.overrideMimeType('text/xml');
    }
else if (window.ActiveXObject) { // IE
        try {
            var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!xmlhttp) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
return xmlhttp;
}

var xmlHttp = createRequestObject();

function showResult(str) {
  if (str.length==0) {
      var div = document.getElementById('livesearch');
      div.innerHTML="";
      div.style.border="0px";
      alert('Some error message here');
  } else {
      var url="livesearch.php";
      url=url+"?q="+str;
      url=url+"&sid="+Math.random();
      //first we open the file
      xmlHttp.open("GET",url,true);
      //now we send anything that needs to be sent
      xmlHttp.send(null);
      //The stateChanged function will be called when ever the
      //readyState changes.
      xmlHttp.onreadystatechange=stateChanged;

  }
}

function stateChanged() {
    //the file has finished processing when the ready state is 4
  if ((xmlHttp.readyState==4) && (xmlHttp.status== 200)) {
    var div = document.getElementById('livesearch');
    //now we put the text that was received from the backend file
    //in our content div..
    div.innerHTML=xmlHttp.responseText;
    div.style.border="1px solid #A5ACB2";
  }
}
[/code]


As I said this should work fine.


Good Luck,
Tom




Link to comment
Share on other sites

Thank you for your reply! The example still doesn't work.. because I think there is an issue with the PHP file.

However, with regards to what you said about the code being crap, here is a follow-up question::  I want to have a livesearch option on my site that uses my RSS xml file for the search results, and I want to do it the right way.  Could you help me with this, because I am new to AJAX and having trouble getting started.

Regardless, thank you for your time and consideration!  Brendan
Link to comment
Share on other sites

Brendan,

I got it to work using a parameterized version of  Tom's script.

Here are the files I used.

Scot L. Diddle, Richmond VA

AJAXLiveSearch.html

[code]

<html>

<head>

<title>
From: http://www.w3schools.com/php/php_ajax_livesearch.asp
</title>

<script type="text/javascript" src="javascript/AJAXLiveSearch.js"></script>

<style type="text/css">
#livesearch
  {
  margin:0px;
  width:194px;
  }
#txt1
  {
  margin:0px;
  }
</style>

</head>

<body>

<!-- document.getElementById('"id=name"').value -->

<form>

<input type="text" id="txt1" size="30" onkeyup="showResult(this.value,'area1');">

<br />
<br />

<div id="area1"></div>

<!-- OR: -->

<br />

<input type="text" id="txt2" size="30" onkeyup="showResult(document.getElementById('txt2').value,'area2');">

<br />
<br />

<div id="area2"></div>


</form>

</body>
</html>

[/code]

javascript/AJAXLiveSearch.js

[code]


// From http://www.phpfreaks.com/forums/index.php/topic,124823.0.html
// because according to the post listed above from AJAX Freaks, the one at
// http://www.w3schools.com/php/php_ajax_livesearch.asp was broken.

//obers request object
function createRequestObject() {

    if (window.XMLHttpRequest) { // Mozilla, Safari, Opera...
        var xmlhttp = new XMLHttpRequest();
        if (xmlhttp.overrideMimeType)

xmlhttp.overrideMimeType('text/xml');
}

else if (window.ActiveXObject) { // IE
        try {
            var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
        try {
            var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {}
        }
    } // END else if IE

    if (!xmlhttp) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }

return xmlhttp;

} // END function createRequestObject() {

var xmlHttp = createRequestObject();

function showResult(str,DIVName) {

currDIVName = DIVName;

  if (str.length==0) {

      var div = document.getElementById(currDivName);
      div.innerHTML="";
      div.style.border="0px";
      alert('Some error message here');

  }
  else {
      var url="./AJAXLiveSearch.php";
      url=url+"?q="+str;
      url=url+"&sid="+Math.random();
      //first we open the file
      xmlHttp.open("GET",url,true);
      //now we send anything that needs to be sent
      xmlHttp.send(null);
      //The stateChanged function will be called when ever the
      //readyState changes.
      xmlHttp.onreadystatechange=stateChanged;

  }
} // END function showResult(str)

function stateChanged() {
    //the file has finished processing when the ready state is 4
  if ((xmlHttp.readyState==4) && (xmlHttp.status== 200)) {
    var div = document.getElementById(currDIVName);
    //now we put the text that was received from the backend file
    //in our content div..
    div.innerHTML=xmlHttp.responseText;
    div.style.border="1px solid #A5ACB2";
  }
} // END function stateChanged()

[/code]

./AJAXLiveSearch.php

[code]

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("AJAXLiveSearchlinks.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;

?>

[/code]

AJAXLiveSearchLinks.xml

[code]

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited with XML Spy v2006 (http://www.altova.com) -->
<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>

[/code]




Link to comment
Share on other sites

Scot, thank you so much for your reply!

However, I am still getting an error:: "Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /web/kilbad.com/DEVELOPMENT/ajax/AJAXLiveSearch.php on line 16"

Could it have to do with the version of PHP I am using (PHP Version 4.4.2-pl2-gentoo)?  It seems as if the error is occurring at the same spot it initially was before?

I posted your example at [url=http://www.kilbad.com/DEVELOPMENT/ajax/AJAXLiveSearch.html]http://www.kilbad.com/DEVELOPMENT/ajax/AJAXLiveSearch.html[/url]

Thanks again! Brendan
Link to comment
Share on other sites

Brendan,

Line 16 in the PHP says: $y=$x->item($i)->getElementsByTagName('title');

I looked up getElementsByTagName, and it pointed to:

http://www.php.net/manual/en/ref.dom.php

Which says:

XXX. DOM Functions
Introduction

The DOM extension allows you to operate on XML documents through the DOM API with PHP 5.

For PHP 4, use DOM XML.

I use PHP 5, and have never used DOM XML. 

The race is on to see which of us can re-generate the PHP program to work in PHP 4 first.  :D

Scot L. Diddle, Richmond VA


Link to comment
Share on other sites

  • 1 year later...

ScotDiddle. Hi, i'm having similar problems. I can get the search bar to show "no suggestions" but unfortunatley thats all it will show. I'm using your code but i'm having trouble with the filename change. Did you put the js file in its own javascipt folder? Plus the php file i noticed had a ./ in front. These might seem like ridiculous questions to you but i've only just got my own webspace and i guess i'm a bit overly cautious. Thanks for any help you have time to give :)

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.