Home > Back-end >  Modification of Ajax Live Search to include a new field
Modification of Ajax Live Search to include a new field

Time:08-08

https://www.w3schools.com/php/php_ajax_livesearch.asp

I am trying to modify the code in the tutorial for an ajax live search, to include a new field called keyword. I want the search to also search the keyword field in order to improve user experience.

I have already modified the link.xml fine to include the newly added keyword tag.

 <link>
<title> title </title>
<keyword> keywords here </keyword>
<url>https://path to url</url>
 </link>

I am kind of stuck in the area below, trying to modify the conditional statement.

<?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');
    $k=$x->item($i)->getElementsByTagName('keyword'); // New field added 
    $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 was found
// or to the correct values
if ($hint=="") {
  $response="no suggestion";
} else {
  $response=$hint;
}

//output the response
echo $response;
?>

CodePudding user response:

I think you can change the condition

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

to

$checkTitle = stristr($y->item(0)->childNodes->item(0)->nodeValue,$q);
$checkKeyword = stristr($k->item(0)->childNodes->item(0)->nodeValue,$q);
if ($checkTitle || $checkKeyword) {
   //
}
  • Related