JQuery tokeninput: [Error] TypeError: undefined is not an object (evaluating 'term.replace')

610 views Asked by At

I'm using http://loopj.com/jquery-tokeninput/ because I needed to interface a select box directly to DB.

I wrote the PHP script that accept GET request like explained on his GitHub:

<?php
require_once('sondaggio.php');
# Connect to the database
$s = new Sondaggio();
# Perform the query
$query = sprintf("SELECT id, nome from Regioni WHERE nome LIKE '%s%' LIMIT 5", $s->getRealEscapeString($_GET["q"]));
$arr = array();
$arr = $s->readFromDB($query);
# JSON-encode the response
$json_response = json_encode($arr);
# Return the response
echo $json_response;
?>

Class Sondaggio constructor:

function __construct(){
    $this->conn = new mysqli($this->host, $this->user, $this->password, $this->database);
    // Check connection
    if ($this->conn->connect_error) {
        exit("Connection failed: " . $this->conn->connect_error);
    }
}

function readFromDB($query):

public function readFromDB($query){
    $arr = array();
    $result = $this->conn->query($query);
    if ($result->num_rows > 0){
        while($row = $result->fetch_object()) {
            $arr[] = $row;
        }
    }
    return $arr;
}

All is tested and works good, the output is correct following his documentation. However I get an error when I start to type into the selectbox:

[Error] TypeError: undefined is not an object (evaluating 'term.replace')
regexp_escape (jquery.tokeninput.js:828)
find_value_and_highlight_term (jquery.tokeninput.js:844:88)
(anonymous function) (jquery.tokeninput.js:899)
each (jquery.min.js:2:11781)
populateDropdown (jquery.tokeninput.js:896)
success (jquery.tokeninput.js:1031)
o (jquery.min.js:2:14739)
fireWith (jquery.min.js:2:15504)
w (jquery.min.js:4:12484)
d (jquery.min.js:4:18320)

So I'm stuck with this error and I don't know why it appears, please help me. Thank you

EDIT:

var_dump($json_response) (with ...php?q=t) output:

string(75) "[{"id":"16","nome":"Toscana\r"},{"id":"17","nome":"Trentino-Alto Adige\r"}]"
1

There are 1 answers

1
big On

Solved, just a mistake. According to http://loopj.com/jquery-tokeninput/ documentation:

Your script should output JSON search results in the following format:

[ {"id":"856","name":"House"}, {"id":"1035","name":"Desperate Housewives"}, ... ]

Here fields are 'id' and 'name'. My query instead asked the DB for 'id' and 'nome':

$query = sprintf("SELECT id, nome from...

So I just updated the query like this:

$query = sprintf("SELECT id, nome as name from...

Now all works correctly!