Show json data as drop-down menu


JSON Live Data Search using Ajax JQuery

Employee Data

Below is the complete code example you can use for live searching employee data with Ajax and jQuery. Copy it into your project files, but here it will display as code for readers:


<div class="container" style="width: 900px;">
  <h2 align="center">JSON Live Data Search using Ajax JQuery</h2>
  <h3 align="center">Employee Data</h3>  
  <div align="center">
    <input class="form-control" id="search" name="search" type="text" placeholder="Search employee..." />
  </div>
  <ul class="list-group" id="result"></ul>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $.ajaxSetup({ cache: false });
  
  $('#search').keyup(function(){
    $('#result').html('');
    var searchField = $('#search').val();
    var expression = new RegExp(searchField, "i");
    
    $.getJSON('data.json', function(data) {
      $.each(data, function(key, value){
        if (value.name.search(expression) != -1 || value.location.search(expression) != -1) {
          $('#result').append(
            '<li class="list-group-item link-class">' +
            '<img src="'+value.image+'" height="40" width="40" class="img-thumbnail" /> ' +
            value.name+' | <span class="text-muted">'+value.location+'</span></li>'
          );
        }
      });  
    });
  });
  
  $('#result').on('click', 'li', function() {
    var click_text = $(this).text().split('|');
    $('#search').val($.trim(click_text[0]));
    $("#result").html('');
  });
});
</script>

<!-- Sample JSON file (data.json) -->
[
  {
    "name":"Angel Lewis",
    "image":"https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/3/000/0d4/2f7/07a3d35.jpg",
    "location":"Seattle, WA"
  },
  {
    "name":"Justin Dean",
    "image":"https://media.licdn.com/mpr/mpr/shrink_100_100/AAEAAQAAAAAAAAIMAAAAJGExNTE4OWY4LWU4ODMtNDA2ZS1iNWI1LWNkYmIyOWMyMGQ5Zg.jpg",
    "location":"Muscatine, IA"
  },
  {
    "name":"Nora Blake",
    "image":"https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/2/005/0b8/118/387e091.jpg",
    "location":"Seattle, WA"
  }
  // ... more employee records
]

Comments

Post a Comment

Popular posts from this blog

Simple PHP Mysql Shopping Cart

How to seperate character from string in php

How to Delete record using PHP Ajax