开发者

Please help me to solve problem with Autocomplete

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", "user", "pass");
mysql_select_db("db", $conn);
$q = strtolower($_GET["term"]);
$query = mysql_query("select fullname from usr_table where fullname like %$q%");
$results = array();
while ($row = mysql_fetch_array($query)) {
    array_push($results, $row);
}
echo json_encode($results);

Autocomplete doesn't work for me. Can't find wrong part of code. Please help to solve this problem. Sorry for my bad english


You mentioned you want to create an array of IDs (most likely associated with each searched name)?

In your SQL statement, include your ID field.

$query = mysql_query("select id, fullname from usr_table where fullname like %$q%");

Then, instead of

array_push($results,$row)

Try:

$results[] = array( $row[0] => $row[1] ); 

This should follow the same array structure as the static array from search.php before you modified it after it is JSON encoded. I'm not sure which your autocomplete will grab to output as your results, so try this as well (switch row[0] with row[1])

$results[] = array( $row[1] => $row[0] );

EDIT:

Now, that I know what the JSON encoded array need to look like. Do this instead:

$results[] = array ( "id" => $row[0] , "label" => $row[1], "value" => $row[1] );

The above appends the array to the results array. Let me know if this works. It is equivalent to array_push:

array_push($results, array ( "id" => $row[0] , "label" => $row[1], "value" => $row[1] ));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜