jQuery + PHP Autocomplete

和自甴很熟 提交于 2021-02-08 10:25:00

问题


I recently upgraded jQuery from 1.8.x to 1.11.3 because of another dependency, and my autocomplete is now broken. I've been searching this site, Google, etc.. all day and cannot come up with the answer. jQuery-UI version is 1.9.2.

To start, I have a PHP file (autocomplete.php) that queries a MySQL database and returns inventory information:

<?php
require_once 'database.php';


if ($stmt = $con->prepare("select item_no, item_desc_1, item_desc_2 FROM items")) {
$stmt->execute();

$name = array();

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $name[] = TRIM($row['item_no']) . '|' . TRIM($row['item_desc_1']) . '|' . TRIM($row['item_desc_2']);
};
echo json_encode($name);
}
?>

So far so good. I can check that the results are returned in the proper format.

On the page where I want the autocomplete, once the item_no is selected from the autocomplete results, item_desc_1 and item_desc_2 are populated from the results:

<input id="item_no" name="item_no" placeholder="Enter Item#" class="form-control" tabindex="2" type="text" />
<input id="item_desc_1" name="item_desc_1" placeholder="Enter Item Desc 1" class="form-control" type="text">
<input id="item_desc_2" name="item_desc_2" placeholder="Enter Item Desc 2" class="form-control" type="text">

At the very bottom of the page is my script, which should return the 3 elements from the JSON results and populate the fields.

$(function() {
var availableItems = <?php include('autocomplete.php'); ?>;
$("#item_no").autocomplete({
    source: availableItems.map(function(elem){
        return { 'label': elem.split('|')[0], 'value': elem.split('|')[1],'value2': elem.split('|')[2] }
    }),
    select: function(event, ui){
        $('#item_no').val(ui.item.label);
        $('#item_desc_1').val(ui.item.value);
        $('#item_desc_2').val(ui.item.value2);
        return false;
    }
   });
});

I keep getting either Uncaught TypeError: Cannot read property 'split' of null (Chrome) or TypeError: elem is null (Firebug).

To troubleshoot, I updated the table so there can't be NULL values in the table - if a value is NULL in either item description field then 'No Description Found' is returned. item_no is a primary key and NULL is not allowed.

What am I missing?


回答1:


The issue ended up being non-ascii characters stored in the database. Once I removed them, everything worked as expected. Thanks for everyone's help



来源:https://stackoverflow.com/questions/34732747/jquery-php-autocomplete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!