Autocomplete search makes it easier to find an item from the long list of available items.
It displays suggestions based on the typed searched text.
If your data available in XML format then also you can use it for autocomplete searching.
With the use of XPath navigate on the XML data node and search the value.
In this tutorial, I am using the select2 plugin for autocomplete data with jQuery AJAX.
Contents
1. XML Data
Create employeeXML.xml
file.
<?xml version="1.0" encoding="UTF-8" ?> <employees> <employee> <id>1</id> <name>Yogesh Singh</name> <salary>40000</salary> <gender>Male</gender> </employee> <employee> <id>2</id> <name>Sonarika Bhadoria</name> <salary>42000</salary> <gender>Female</gender> </employee> <employee> <id>3</id> <name>Anil Singh</name> <salary>36000</salary> <gender>Male</gender> </employee> <employee> <id>4</id> <name>Mayank Patidar</name> <salary>39000</salary> <gender>Male</gender> </employee> <employee> <id>5</id> <name>Priya</name> <salary>23000</salary> <gender>Female</gender> </employee> <employee> <id>6</id> <name>Ravi Sharma</name> <salary>43000</salary> <gender>Male</gender> </employee> <employee> <id>7</id> <name>Akilesh Sahu</name> <salary>39000</salary> <gender>Male</gender> </employee> <employee> <id>8</id> <name>Rohan pathak</name> <salary>42000</salary> <gender>Male</gender> </employee> <employee> <id>9</id> <name>Madhu sharma</name> <salary>30000</salary> <gender>Female</gender> </employee> <employee> <id>10</id> <name>Sunil singh</name> <salary>38000</salary> <gender>Male</gender> </employee> </employees>
2. HTML
Include select2.min.css, select2.min.js files, and also a jQuery library.
I used CDN for including the select2 library. You can also download the library from here and include it in the file.
Create a <select>
element.
Completed Code
<!-- CSS --> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <!-- Script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <!-- Dropdown --> <select id='selEmployee' style='width: 200px;'> <option value='0'>- Search Employee -</option> </select>
3. PHP
Create a new ajaxfile.php
file.
Load File and create an object –
Read POST searchTerm
and assign in $searchText
in lower case.
Load xmlfile.xml
and create an object of DOMXPath
.
Using $xpath
object to create the expressions for searching.
By default, XPath performs case-sensitive searching. For a case-insensitive search, I am using strtolower
function to convert node value in lower case and perform searching.
To use strtolower
function in expression need to register it to XPath object using registerNamespace
and registerPhpFunctions
functions.
Expression Creation –
Now create an expression to select all nodes of <employee>
which contains search text on <name>
nodes.
//employee[contains(php:functionString('strtolower',name), '$searchText')]/id
Loop on the selected result and initialize $response
Array if $val->tagName
is equals to 'id'
or 'name'
.
If $val->tagName == 'id'
then initialize
$response[$count]['id']
with node value. Similarly, initialize $response[$count]['text']
with
node value if $val->tagName == 'name'
.
Return $response
in JSON format.
Completed Code
<?php // Search Text $searchText = ""; if(isset($_POST['searchTerm'])){ $searchText = strtolower($_POST['searchTerm']); } // Load XML File $doc = new DOMDocument(); $doc->load("xmlfile.xml"); $xpath = new DOMXPath($doc); // Register PHP function $xpath->registerNamespace('php', 'http://php.net/xpath'); $xpath->registerPhpFunctions('strtolower'); // Allow all PHP functions // Execute query and select all nodes $results = $xpath->query("//employee[contains(php:functionString('strtolower',name), '$searchText')]/*"); $count = 0; $response = array(); foreach($results as $val){ if($val->tagName == 'id'){ $response[$count]['id'] = $val->nodeValue; } if($val->tagName == 'name'){ $response[$count]['text'] = $val->nodeValue; $count++; } } echo json_encode($response_arr); exit;
4. jQuery
Initialize select2 on <select id='selEmployee'>
element.
Use ajax
option to send AJAX request to ajaxfile.php
file to get data.
Pass typed value using data
and on successfully callback handle response with processResults
.
Completed Code
$(document).ready(function(){ // Initialize select2 $("#selEmployee").select2({ ajax: { url: "ajaxfile.php", type: "post", dataType: 'json', delay: 150, data: function (params) { return { searchTerm: params.term // search term }; }, processResults: function (response) { return { results: response }; }, cache: true } }); });
5. Demo
6. Conclusion
I used the select2 jQuery plugin for implementing autocomplete functionality. You can use any other plugin if you want.
Modify the XPath expression according to your XML data structure for searching.
You can learn more XPath expression creation from here.
If you found this tutorial helpful then don't forget to share.