nanobash
nanobash

Reputation: 5500

get result with jquery ajax from autocomplete

I'm using jQuery autocomplete and want to retrieve data from php file called some.php, in which is only written

<?php
echo "Hello World";
?>

and here is javascript

<script type="text/javascript">
$(function(){
    $("#key").autocomplete({
        source: function(){
            $.ajax({
                type: "POST",
                url: "./some.php",
                data: {key: $("#key").val()},
                success: function(result){
                    // what code is needed here to be placed
                }
            });
        }
    });
});
</script>

and html by the way =>

<input type="text" name="key" id="key">

I think script is written correctly , because when I'm writing in success function alert(result) it gets "Hello world", but I want it to be in drop down box , how can fix this problem , please help me , thanks :)

Upvotes: 0

Views: 525

Answers (2)

ori
ori

Reputation: 7847

$("#key").autocomplete({
    source: function(request, response){
        $.ajax({
            type: "POST",
            url: "./some.php",
            data: {key: request.term},
            success: function(result){

                response(result);
            }
        });
    }
});

response(result) will display the autocomplete menu -- result should be an array of items (where each item is a string or an object with value or label keys).

As SJ GJ mentioned, you can simply set source: "./some.php" but then some.php needs to be modified to accept the request parameter term and return a json array of items.

Upvotes: 2

csotelo
csotelo

Reputation: 1485

try this:

JS:

<script type="text/javascript">
$(function(){
    $("#key").autocomplete({
        source: "./some.php"
    });
});
</script>

PHP:

$result = array('1' => 'Hello World');

echo json_encode($result);

Upvotes: 1

Related Questions