Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autocomplete doesn't work properly

I want to apply "Jquery UI Autocomplete with multiple values" to one registration forms input field.

What i want to do exactly: When visitor types name of existing user to this input field, first of all, script searches for name existence, completes it (if exists), adds comma. User can type second, third... existing usernames to this field, and everytime script will auto complete. And when visitor clicks to submit button, PHP searches for id's of this usernames, creates array of id's, adds it to new users "friends" field in db table.

My code:

HTML

<form action="index.php" method="post">      
<input class="std" type="text" name="friends"  id="friends"/>
<input type="submit" name="submit">
</form>

Jquery

$(function() {
    function split( val ) {
        return val.split( /,\s*/ );
    }
    function extractLast( term ) {
        return split( term ).pop();
    }

    $( "#friends" )
        // don't navigate away from the field on tab when selecting an item
        .bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                    $( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        })
        .autocomplete({
            source: function( request, response ) {
                $.getJSON( "search.php", {
                    term: extractLast( request.term )
                }, response );
            },
            search: function() {
                // custom minLength
                var term = extractLast( this.value );
                if ( term.length < 2 ) {
                    return false;
                }
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( ", " );
                return false;
            }
        });
});

this is original php file from sample folder which works perfectly. but i want to fetch from database instead of array
Original search.php

$q = strtolower($_GET["term"]);
if (!$q) return;
$items = array(
"Great Bittern"=>"Botaurus stellaris",
"Little Grebe"=>"Tachybaptus ruficollis",
"Black-necked Grebe"=>"Podiceps nigricollis",
"Little Bittern"=>"Ixobrychus minutus",
"Black-crowned Night Heron"=>"Nycticorax nycticorax",
"Purple Heron"=>"Ardea purpurea",
"White Stork"=>"Ciconia ciconia",
"Spoonbill"=>"Platalea leucorodia",
"Red-crested Pochard"=>"Netta rufina",
"Common Eider"=>"Somateria mollissima",
"Red Kite"=>"Milvus milvus",

);

function array_to_json( $array ){

    if( !is_array( $array ) ){
        return false;
    }

    $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
    if( $associative ){

        $construct = array();
        foreach( $array as $key => $value ){

            // We first copy each key/value pair into a staging array,
            // formatting each key and value properly as we go.

            // Format the key:
            if( is_numeric($key) ){
                $key = "key_$key";
            }
            $key = "\"".addslashes($key)."\"";

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = "\"".addslashes($value)."\"";
            }

            // Add to staging array:
            $construct[] = "$key: $value";
        }

        // Then we collapse the staging array into the JSON form:
        $result = "{ " . implode( ", ", $construct ) . " }";

    } else { // If the array is a vector (not associative):

        $construct = array();
        foreach( $array as $value ){

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = "'".addslashes($value)."'";
            }

            // Add to staging array:
            $construct[] = $value;
        }

        // Then we collapse the staging array into the JSON form:
        $result = "[ " . implode( ", ", $construct ) . " ]";
    }

    return $result;
}

$result = array();
foreach ($items as $key=>$value) {
    if (strpos(strtolower($key), $q) !== false) {
        array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
    }
    if (count($result) > 11)
        break;
}
echo array_to_json($result);

Changed search.php

$conn = mysql_connect("localhost", "tural", "0579ural")  or die( mysql_error() );;
mysql_select_db("askon", $conn)  or die( mysql_error() );;
$q = strtolower($_GET["term"]);
if (!$q) return;
$query = mysql_query("select id, fullname from usr_table where fullname like '$q%'")  or die( mysql_error() );;
$results = array();
while ($row = mysql_fetch_array($query)) {
   $results[] = array( $row[1] => $row[0] );
}
echo json_encode($results);

Autocomplete php script works prntscr.com/22mxl but i think something wrong with jquery: it doesn't show menu. prntscr.com/22mxg. How to solve this issue? P.S FOR ORIGINAL SEARCH.PHP IT RETURNS something like this prntscr.com/22n0e and shows prntscr.com/22n0r.

like image 904
Tural Ali Avatar asked Jun 16 '11 16:06

Tural Ali


1 Answers

SemanticScuttle does what you want:

  • jQuery autocomplete setup
  • Ajax callback

Have a look at the (working) first file, it should give you enough hints to get yours working.

like image 120
cweiske Avatar answered Oct 02 '22 09:10

cweiske