0

So basically I have a intranet for a business where the employees can login and do various tasks. In order to inprove efficency I have implemented what I am calling the "QuickTask" feature where the employees can select a task via a drop down menubefore they log in so it can go straight to it. Due to there being various departments, I have made a script where the employees can type in their username and press the submit button it populates the list of tasks relevant to their department, this is only temporary as the submit button needs to be used to actually login. However, I would like to change this so the list would populate as they type their username. How could I do this?

I have 3 files.

1. index.php (Log in page)

2. quickTask.js (jQuery function)

3. determine_department.php (The file quickTask.js is communicating with)

Here is the code:

index.php:

<form action="javascript:void(0);" method="post">
    Username: <input type="text" id="username" name="username" /><br />
    Password: <input type="password" name="password" /><br />
    <i>QuickTask:</i><div id="quickTask"></div>
    <br />
    <a href="reset_password.php">Forgot Password?</a><br />
    <input class="test" type="submit" id="thing" value="Log In" />
</form>

quickTask.js

$(document).ready(function() {
    $('input#thing').on('click', function() {
        var username = $('input#username').val();
        if ($.trim(username) != '') {
            $.post('../inc/determine_department.php', {
                username: username
            }, function(data) {
                $('div#quickTask').html(data);
            });
        }
    });
});

determine_department.php:

<?php

$username = $_POST['username'];

if(isset($username) === true && empty($username) === false) {

    mysql_connect("localhost", "root", "24Bottlesofgin24");
    mysql_select_db("intranet");

    $sql = "SELECT DEPARTMENT FROM `employees` WHERE USERNAME='$username'";
    $result = mysql_query($sql);

    while($row = mysql_fetch_array($result)){
        $depID = $row['DEPARTMENT'];
    }

    $sql2 = "SELECT * FROM `quicktask` WHERE DEP_ID='$depID'";
    $result2 = mysql_query($sql2);
    echo "<select name=\"QT\">";
    echo "<option value=\"\" selected=\"selected\" disabled>-- Please Pick One --</option>";
    while($row2 = mysql_fetch_array($result2)){
        echo "<option value=\"" . $row2['DEP_ID'] . "\">" . $row2['TASK'] . "</option>";
    }
    echo "</select>";

}

?>

Here is a live example:

Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
Stefano
  • 93
  • 2
  • 7
  • If you have no idea how to do that, I suggest you look for an autocomplete pugin. [jQueryUI](http://jqueryui.com/) includes one, and [bootstrap](http://twitter.github.com/bootstrap/) too. – bfavaretto Aug 20 '12 at 18:55
  • Who is voting to close everything?! Crazy. Every question I've been in today. – CaffGeek Aug 20 '12 at 19:11

5 Answers5

2

Here is what you want, converted from How to delay the .keyup() handler until the user stops typing? to your needs. It will run the query if/when the user stops typing for 200 ms, the time is set by the second parameter to delay, you can have it for any amount of time you like. However, I am really with those who suggest using an autofill plugin - why reinvent the wheel?

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();


$(document).ready(function() {
    $('input#username').on('keyup', function() {
        delay(function(){
          var username = $('input#username').val();
        if($.trim(username) != '') {
            $.post('../inc/determine_department.php', {username: username}, function(data){
                $('div#quickTask').html(data);
            });
        }

        },200)
    });

    });
Community
  • 1
  • 1
Liam Bailey
  • 5,879
  • 3
  • 34
  • 46
  • That's pretty much what I was trying to say...but with actual code. – CaffGeek Aug 20 '12 at 19:05
  • sorry buddy, I was looking up and typing while you guys were chatting. Just saw the thread – Liam Bailey Aug 20 '12 at 19:06
  • +1. In addition, I think a hybrid would be nice. Have a delay like you have but cache the list first time around and only refresh the cached list on another set delay. Or the php file could cache the list instead for a period of time. I know OP said list could change but I doubt a list of usernames changes every 10 seconds or even every minute. Caching it for a time limit could be meeting a nice medium between efficiency and usability. – Nope Aug 20 '12 at 19:12
  • If I may wade in, in my view most people in a company will know their username, and prob won't stop typing until done. Therefore having the delay should mean only one request and a very short list. But I am one for caching rather than multiple requests usually – Liam Bailey Aug 20 '12 at 19:14
  • @FrançoisWahl, Remember the list being cached isn't of usernames. This isn't a typical autocomplete, It's of tasks they have access to based on their department (found from the username) – CaffGeek Aug 20 '12 at 19:46
0
$('input#username').on('keyup', function() {...});

but better be sure to only run a single ajax request at a time.

Andreas Linden
  • 12,489
  • 7
  • 51
  • 67
0

Change

 $('input#thing').on('click', function() {

to

 $('input#username').on('keyup', function() {

Should do it, you want the keyup event on the #username input instead of the click event of #thing

CaffGeek
  • 21,856
  • 17
  • 100
  • 184
  • While technically this may answer the question, firing a new ajax request on every keyup event is not recommended. – bfavaretto Aug 20 '12 at 18:56
  • 2
    You should assign the ajax request to a variable and abort the existing one on keyup – Austin Aug 20 '12 at 18:57
  • Some flood control would need to be incorporated using a setTimeout. So it delays the lookup a half second, and if the even is triggered again (another key pressed) it cancels the previous setTimeout, and creates a new one – CaffGeek Aug 20 '12 at 18:57
  • Why go through all of the trouble of using setTimeout and timed functions when you can simply abort the existing request on keyup? – Austin Aug 20 '12 at 18:59
  • With setTimeout you can ensure the request is never started in the first place. – CaffGeek Aug 20 '12 at 18:59
  • But there is a delay of 500ms, with the method I proposed, there is no delay. Either this, or _use ajax only once_ and cache a list of _all_ the names if there aren't an obscene amount. No need to send multiple requests when matching can be done on the client side. – Austin Aug 20 '12 at 19:00
  • @Austin, regardless, that's an implementation detail. On an intranet, a few extra calls aren't a big deal anyhow. – CaffGeek Aug 20 '12 at 19:01
  • But why? It is a better practice to cache a list than to send to the server multiple times to get the same result. Intranet or not, AJAX is doing more work than needs to be done. – Austin Aug 20 '12 at 19:02
  • @Austin, list could change. I prefer to wait for a pause in typing to load it. – CaffGeek Aug 20 '12 at 19:03
  • Think about the implementation. The program is run on an intranet of a small business. I doubt they will be adding users so quickly that the initial call will miss any. – Austin Aug 20 '12 at 19:06
  • @Austin, it's easy, see Liam's answer. – CaffGeek Aug 20 '12 at 19:10
0

Basically, the click function will still them same. You just need to affect it to the keyup event of your username input :

$('#username').keyup( function() {
    var username = $('input#username').val();
    if($.trim(username) != '') {
        $.post('../inc/determine_department.php', {username: username}, function(data){
            $('div#quickTask').html(data);
        });
    }
});
0

javascript:

$('input#thing').keyup(function()

mysql:

    $sql = "SELECT * FROM `quicktask` WHERE DEP_ID IN (SELECT DEPARTMENT FROM `employees` WHERE USERNAME like '".$username."%')";
    $result = mysql_query($sql);
    echo "<select name=\"QT\">";
    echo "<option value=\"\" selected=\"selected\" disabled>-- Please Pick One --</option>";
    while($row = mysql_fetch_array($result)){
        echo "<option value=\"" . $row['DEP_ID'] . "\">" . $row['TASK'] . "</option>";
    }
    echo "</select>";
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107