-2

I have a text field whereby a user can search for a last name. When they start typing then a search is performed on the database via php/ajax. This then displays names in an unordered list. At this point I am just trying to alert the id of that user if you click on the <li>.

PHP for the ajax call:

if ($_POST) {
    $search = "{$_POST['last_name']}%";
    $stmt = $link->prepare("SELECT `first_name`, `last_name`, `id` FROM `employees` WHERE `last_name` LIKE ? LIMIT 7");
    $stmt->bind_param("s", $search);
    $stmt->execute();
    $result = $stmt->get_result();
    $numRows = $result->num_rows;
    if ($numRows > 0) {
        echo "<ul id='myid'>";
        while ($row = $result->fetch_assoc()) {
            $first_name = sanitize($row['first_name']);
            $last_name = sanitize($row['last_name']);
            $id = sanitize($row['id']);
            echo "<li data-id='$id'>" . $last_name . " , " . $first_name . "</li>";
        }

        echo "</ul>";
    }
    else {
        echo "No results found";
    }

    $stmt->close();
}

jQuery

$(document).ready(function(){ 
            $( "#last_name" ).focus();
            $( "#last_name" ).keyup(function(){
            $( "#loading" ).show();
            var last_name = $( "#last_name" ).val();
                if(last_name.length > 2) {

                $.ajax({

                    type: 'POST',
                    url: 'functions/employee-search.php',
                    data: {last_name: last_name},
                    success: function(data) {

                        if(!data.error) {
                            $( "#result" ).html(data);
                             $( "#loading" ).hide();

                        }
                    }

                });
            }

                if(last_name.length < 1) {
                    $( "#result" ).html("");
                    $( "#loading" ).hide();
                }

                });

            $("#myid li").click(function() {
                 alert($(this).attr('id'));

        });
    });

HTML

<div class="row">
    <div class="col-md-6">
        <div class="form-group">
            <label class="control-label">Employee</label>
            <input type="text" class="form-control" name="last_name" placeholder="Search by surname" id="last_name" autocomplete="off">
            <div style="display:none" id=loading><img src="../plugins/images/ajax-loader.gif" /></div>
            <div id="result"></div>
        </div>
    </div>
</div>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Iggy's Pop
  • 589
  • 1
  • 6
  • 24
  • 2
    what's not working for you? did you check your console and for errors? – Funk Forty Niner May 04 '17 at 18:30
  • No console errors. The alert is not working i.e.: no alert pops up with the ID value. – Iggy's Pop May 04 '17 at 18:40
  • what about `$("ul#myid > li").click(function() { var id = $(this).attr('data-id'); alert(id); }` ? also, make sure PHP has no error, adding `error_reporting(E_ALL); ini_set('display_errors', 1);` on top of your PHP page – OldPadawan May 04 '17 at 18:53

2 Answers2

1

If I understand the issue correctly you need to use data rather than attr.

If you use attr you are saying, get me the value of the id attribute but in your code the id value is actually stored in the data-id attribute.

Try changing this line:

alert($(this).attr('id'));

To this:

alert($(this).data('id'));

Or:

alert($(this).attr('data-id'));

You can read more about the data function here: https://api.jquery.com/data/

Also as you are adding elements to the DOM via AJAX the click event will work. You need to change this line:

$("#myid li").click(function() {

To this:

$("#result").on('click', '#myid li', function() {
David Jones
  • 4,275
  • 6
  • 27
  • 51
  • Thanks so much for the info. I changed the code as you suggested but still no alert. No errors in console either. Is there not an issue with the php or is it okay? – Iggy's Pop May 04 '17 at 18:44
  • @Jonathan Ah I thought you did but it didn't contain the correct value. Might be worth updating the question to say what is happening now and what is the desired outcome of the code. I updated my answer based on that new information. – David Jones May 04 '17 at 18:47
  • off topic, but why did I get -2 for my question? I don't understand how that works. – Iggy's Pop May 04 '17 at 19:12
  • This works: `$(document).on("click","#myid li",function() { alert($(this).data('id')); });` – Iggy's Pop May 04 '17 at 19:14
  • @Jonathan it means two people downvoted your question. Not sure why but sometimes it means your question could have contained more detail to help people answer it – David Jones May 04 '17 at 19:14
  • @Jonathan yep that would work but I would be careful delegating events to the document. See this answer for more information http://stackoverflow.com/a/12824698/2315558 – David Jones May 04 '17 at 19:17
  • Argh. That sucks. Then I am back to square one. – Iggy's Pop May 04 '17 at 19:21
  • @Jonathan Updated the answer as I saw a mistake. You could attach it to the #result div. Anyway hope I pointed you in the right direction! – David Jones May 04 '17 at 19:25
  • `$("#result").on("click","li",function() { $("#last_name").val($(this).text()) $("#emp_id").val($(this).data('id'));` – Iggy's Pop May 04 '17 at 19:26
0

jquery

 $("#myid li").click(function() {
                 console.log($(this).attr('id'));
                 console.log($(this).data('id'))

        });
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myid">
<li id="one" data-id="1">one</li>
<li id="two" data-id="2">two</li>
<li id="three" data-id="3">three</li>
</ul>
Jeet
  • 80
  • 5