Skip to content
Advertisement

I am trying to pass letters through ajax to get the first letter of a lastName and link it to the navbar, wrong code? [closed]

I am building a contacts directory (see picture).

enter image description here

On the right there is a nav bar with the alphabet. At the moment all the contacts from the database are showing but what I am trying to do is to only show the ones where the lastName starts by the letter clicked on the nav bar and hide the rest.

So basically when I click to, for example letter B on the nav bar on the right, I want all the contacts with last names starting by the letter B to appear instead of all of the contacts, does this make sense?

I have been suggested to wrap each name into the letter they start with however I have a very large database and I am not really sure how to apply that on php. This is what I have come up with so far.

I have tried this now but not sure where I am going wrong. I think it is in the php when I am trying to implement the sql “like” operator in javascript as I’m probably not using the right method but please if someone could tell me where am I going wrong would be great!

I know I need to use something similar to this but not sure how to apply it:

 $('#nav a').click(function (e) {
      var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      for (var i = 0; i < str.length; i++) {
          var nextChar = str.charAt(i);
          $('#' + nextChar).fadeOut();
      }
      var txt = $(e.target).text();
      $('#' + txt).delay(400).fadeIn();
  });

Or something like:

.click $('.')this $this.id and pass letter on ajax

See my code here:

$(document).ready(function() {
  $.ajax({
    type: 'GET',
    url: 'php/getAll.php',
    dataType: 'json',
    success: function(data, alphabet, sort) {
      alphabet = data.nav;
      var db = data.data;
       for (var letter of alphabet) {
            $("#nav").append(`<li><a href="?firstLetter=${letter}">${letter}</a></li>`); 
        }
      for (let i in db) {
        $('#database').append(`
                <div class="loadProfile col-sm-6 col-md-4" onclick="loadProfile(${JSON.stringify(db[i]).split('"').join("&quot;")})">
                <div class="widget col-3 profile">
                    <div class="widget-simple">
                        <span>
                        <img src="img/user-regulars.svg" alt="avatar" class="widget-image img-circle pull-left animation-fadeIn">
                        </span>
                            <h4 class="widget-content text-left">
                                <span id="fullName">${db[i].lastName}, ${db[i].firstName}</span>
                                <p class="findID" style="font-size:11px; color: rgb(190, 190, 190); display: inline"> - ID: ${db[i].id}</p>
                                <br>
                                <div class="info" style: "overflow: hidden">
                                    <p class=${filterBy == "department"} style="font-size:11px; color: rgb(190, 190, 190); float: left">${db[i].department}</p>
                                    <p class=${filterBy == "location"} style="font-size:11px; color: rgb(190, 190, 190); float: left">, ${db[i].location}</p>
                                    <a href="" class="btn btn-xs btn-primary2 Phone" data-toggle="tooltip" title="" data-original-title="Phone"><i class="fa fa-phone"></i></a>
                                    <a href="mailto:${db[i].email}" rel="prefetch" id="eM" class="btn btn-xs btn-primary Email" data-toggle="tooltip" title="" data-original-title="Email"><i class="fas fa-envelope"></i></a>
                                </div>
                            </h4>
                    </div>
                </div>
                </div>
                `)
      }
      return true;
    }
  })
})

HTML:

<main>
  <div class="container">
    <div class="row">
      <div class="col-md-12 main">
        <div class="block1">
          <div id="nav" class="CharacterContainer"></div>
        </div>
        <div class="row style-alt" id="database">
        </div>
      </div>
    </div>
  </div>
</main>
<?php
$sort = isset($_GET['firstLetter']) ? filter_input(INPUT_GET, 'firstLetter',FILTER_SANITIZE_URL) : "" ; 
    $query = "SELECT p.id, p.lastName, p.firstName, p.jobTitle, p.email, d.name as department, l.name as location FROM personnel p LEFT JOIN department d ON (d.id = p.departmentID) LEFT JOIN location l ON (l.id = d.locationID) WHERE p.lastName LIKE '$sort%' ORDER BY p.lastName ASC" ;
    $result = $conn->query($query);
 <?

Advertisement

Answer

You can use .each loop to iterate through your loadProfile div and then get value of fullName span then split that text using split(",")[0] here 0 will give you value before commas(lastname) . Then use that to see if the first letter matches with a tag text then show that divs else hide .

Demo Code :

$(document).ready(function() {
  //suppose data look like this
  var data = {
    "nav": ["A", "B", "All"],
    "data": [{
      "lastName": "Abc",
      "firstName": "avcd"
    }, {
      "lastName": "Bbc",
      "firstName": "avcd"
    }, {
      "lastName": "Abc",
      "firstName": "avcd"
    }]
  }
  alphabet = data.nav;
  var db = data.data;
  for (var letter of alphabet) {
    $("#nav").append(`<li><a href="?firstLetter=${letter}">${letter}</a></li>`);
  }
  for (let i in db) {
    $('#database').append(`
                <div class="loadProfile col-sm-6 col-md-4" onclick="loadProfile(${JSON.stringify(db[i]).split('"').join("&quot;")})">
                <div class="widget col-3 profile">
                    <div class="widget-simple">
                        <span>
                        <img src="img/user-regulars.svg" alt="avatar" class="widget-image img-circle pull-left animation-fadeIn">
                        </span>
                            <h4 class="widget-content text-left">                        
                                <span class="fullName">${db[i].lastName}, ${db[i].firstName}</span>
                               
                    </div>
                </div>
                </div>
                `)
  }
})

$('#nav').on('click', 'a', function(e) {
  //get a tag text
  var to_search = $(this).text().toLowerCase().trim()
  e.preventDefault()
  if (to_search != "all") {
    $(".loadProfile").hide() //hide all divs
    //loop through divs
    $(".loadProfile .fullName").each(function() {
      //get last name by using split 
      var value = $(this).text().toLowerCase().trim().split(",")[0]
      //check if char at `0` positon matchs with to_searc
      if (value.charAt(0) == to_search) {
        $(this).closest(".loadProfile").delay(400).fadeIn(); //show same
      }
    })
  } else {
    $(".loadProfile").delay(400).fadeIn();

  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="database"></div>
<div id="nav"></div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement