How to load XML data in jQuery UI autocomplete with PHP
jQuery UI autocompletes enable a textbox to show a suggestion list based on the input.
It allows the loading suggestion list using AJAX.
AJAX response must be in a defined format otherwise, the list wouldn’t show.
You can load XML data if available.
In this tutorial, I show how you can load XML file data in jQuery UI autocomplete using AJAX and PHP.
1. XML File
Create a new xmlfile.xml
file and store it in the project root.
<?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. Download and Include
- Download jQuery and jQuery UI libraries.
- Include jquery-ui.css, jQuery library, and jquery-ui.min.js script.
<!-- jQuery UI CSS --> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> <!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- jQuery UI JS --> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
3. HTML
Create two text type elements.
1st is used to initialize jQuery UI autocomplete and 2nd is to show selected item id from the suggestion list.
Completed Code
<table> <tr> <td>Search employee</td> <td><input type='text' id='search_employee' ></td> </tr> <tr> <td>Selected Employee id</td> <td><input type='text' id='selectemployee_id' /></td> </tr> </table>
4. AJAX
Create ajaxfile.php
file for handling AJAX request.
Assign $_POST['search']
in $searchText
in lowercase if 'search'
is POST. I assigned it in lowercase to perform a case-insensitive search because I am using the XPath query for selecting XML data which by default performs a case-sensitive search.
Load XML file
Create Object of DOMDocument()
Class and pass the XML file path in the load()
method.
Select XML file data
Using the DOMXPath
object to select XML file data.
Create an object of DOMXPath
where pass the DOMDocument
object.
To use strtolower()
function in XPath query need to first register that function to $xpath
object using registerNamespace()
and registerPhpFunctions()
functions.
Prepare a query to select employee
nodes where $searchText
is found in the name
node.
//employee[contains(php:functionString('strtolower',name), '$searchText')]/*
NOTE – Modify the above query according to your XML file structure. You can learn more about XPath query creation from here.
Using contains()
to search on the name
node. Convert the name
node to the lowercase using strtolower()
function. For selecting all nodes use /*
.
Create $count=0;
and $response
Array. $count
is use for $response
Array indexing and $response
to store return response.
Loop on the $results
. Initialize $response
Array with node value if $val->tagName
is equals to 'id'
or 'name'
.
If $val->tagName == 'id'
then assign $response[$count]['value']
with $val->nodeValue
. Similarly, if $val->tagName == 'name'
then assign $response[$count]['label']
with $val->nodeValue
and increment the $count
variable.
Return $response
Array in JSON format.
Completed Code
<?php // Search Text $searchText = ""; if(isset($_POST['search'])){ $searchText = strtolower($_POST['search']); } // 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 node $results = $xpath->query("//employee[contains(php:functionString('strtolower',name), '$searchText')]/*"); $count = 0; $response = array(); foreach($results as $val){ if($val->tagName == 'id'){ $response[$count]['value'] = $val->nodeValue; } if($val->tagName == 'name'){ $response[$count]['label'] = $val->nodeValue; $count++; } } echo json_encode($response); exit;
5. jQuery
Initialize jQuery UI autocomplete on #search_employee
.
Use 'source'
option to load the suggestion list by sending AJAX POST request to the 'ajaxfile.php'
file.
Set dataType to 'json'
pass input value as data. On successful callback pass AJAX response data
to response()
function.
Use the 'select'
option to get a selected suggestion item.
Assign selected item label – ui.item.label
to #search_employee
. Similarly, assign selected item value – ui.item.value
to #selectemployee_id
.
Completed Code
$(document).ready(function(){ $( "#search_employee" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "ajaxfile.php", type: 'post', dataType: "json", data: { search: request.term }, success: function( data ) { response( data ); } }); }, select: function (event, ui) { $('#search_employee').val(ui.item.label); // display the selected text $('#selectemployee_id').val(ui.item.value); // save selected id to input return false; }, focus: function(event, ui){ $( "#search_employee" ).val( ui.item.label ); $( "#selectemployee_id" ).val( ui.item.value ); return false; }, }); });
6. Demo
7. Conclusion
You don’t need to modify the jQuery script for loading XML file data. XML file handle from the PHP script. Load the file and search on the XML data.
Return valid JSON response to the jQuery script.