Make Autocomplete search with XML Data – jQuery AJAX

Autocomplete search make easier to find an item from the long list of available items.

It displays suggestion 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 XML data node and search the value.

In this tutorial, I am using the select2 plugin for autocomplete data with jQuery AJAX.

Make Autocomplete search with XML Data - jQuery AJAX


Contents

  1. XML Data
  2. HTML
  3. PHP
  4. jQuery
  5. Demo
  6. Conclusion

1. XML Data

Create a new 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 select2 library. You can also download the library from here and include in the files.

Create a <select> element.

Completed Code

<!-- CSS -->
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>

<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/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.

Load xmlfile.xml and create an object of DOMXPath.

Using $xpath object to create the expressions for searching.

By default, XPath performs the case-sensitive searching. For 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 <id> nodes of <employee> which contains search text on <name> nodes.

//employee[contains(php:functionString('strtolower',name), '$searchText')]/id

Similarly, select <name> node.

//employee[contains(php:functionString('strtolower',name), '$searchText')]/name

Loop on the selected result and use nodeValue to get the value and initialize response_arr array.

Return response in JSON format.

Completed Code

<?php

// Search Text
$searchText = "";
if(isset($_POST['searchTerm'])){
  $searchText = strtolower($_POST['searchTerm']);
}

// Load XML File
$doc = DOMDocument::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 "id" node
$results = $xpath->query("//employee[contains(php:functionString('strtolower',name), '$searchText')]/id");
$ids_arr = array();
foreach ($results as $val){
  $ids_arr[] = $val->nodeValue;
}

// Execute query and select "name" node
$results = $xpath->query("//employee[contains(php:functionString('strtolower',name), '$searchText')]/name");
$response_arr = array();
$index = 0;
foreach ($results as $val){
  $name = $val->nodeValue;

  $response_arr[] = array("id"=>$ids_arr[$index],"text"=>$name);
  $index++;
}

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 for 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

Click on the drop-down and search text.


6. Conclusion

I used the select2 jQuery plugin for implementing autocomplete functionality. You can 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.

Related Post

Spread the love
  • 1
  • 1
  •  
  •  
  • 1
  •  

4 Comments

  1. This is awesome am gonna try it on my blog, if it works i will surely come back to thank you enough. Meanwhile thanks for sharing

    September 1, 2018
    Reply
  2. ChriStef said:

    Very usually code. Thank you. Please note and try to correct when someone types with caps on the results won’t come up true.

    September 15, 2018
    Reply
    • Yogesh Singh said:

      Thanks for mentioning it. I have fixed the issue.

      September 16, 2018
      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *