Devin
Devin

Reputation: 59

jQuery autocomplete not sending ajax data

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.js"></script>    

$('#query').autocomplete({
        source: 'parts_by_partno.php',
        select: function (event, ui) {
            $("#query").val(ui.item.label); // display the selected text
            $("#hiddenId").val(ui.item.value); // save selected id to hidden input
        }
    });

I'm getting no errors in firebug, but firebug shows this function is not even making a call to the page. What am I doing wrong?

Upvotes: 0

Views: 1329

Answers (3)

mandroid
mandroid

Reputation: 187

Here is the code how I made it work Use each function and it's good to use with multiple fields too.

$('#query').each(function(i, el) {
    el = $(el);
    el.autocomplete({

        // get source using ajax function
        // If you need to send extra parameters to parts_by_partno.php
        // use data: {}
        source: function(request, response) {
            $.ajax({
                type: 'GET',
                url: 'parts_by_partno.php',
                        
                // when you type word in text field
                // el.val() gets a word and ajax sends value of el.val() to server
                data: {id: el.attr('id'), term: el.val()},
              
                success: function(data) {
                    //data - data returned from server
                    response(data);
                },
                dataType:"json"
            })
        }
    });
});

=================== in PHP ===================

$sendArray = array();

$query = "SELECT * FROM ".$table." WHERE name LIKE '".$_GET['term']."%' LIMIT 10"

while($row=mysql_fetch_array(mysql_query($query)){

  array_push($sendArray, $row['name']);

};

echo json_encode($sendArray);

Upvotes: 2

psugar
psugar

Reputation: 1885

Check this out:

http://jsfiddle.net/xJpsL/1/

If I watch the network requests in chrome, it's requesting it properly. You didn't forget script tags, I assume? Incidentally, that third javascript file for autocomplete.js does not exist (nor is it needed as autocomplete is part of the jquery ui file).

Upvotes: 2

JIA
JIA

Reputation: 1495

wrap the code in the ready handler

$(function(){
 $('#query').autocomplete({
        source: 'parts_by_partno.php',
        select: function (event, ui) {
            $("#query").val(ui.item.label); // display the selected text
            $("#hiddenId").val(ui.item.value); // save selected id to hidden input
        }
    });

});

Upvotes: 0

Related Questions