Select2.js error: Cannot read property 'length' of undefined
Asked Answered
H

3

5

I am using Select2 jquery plugin and I can't get results with json. When looking json response in browser it looks ok. Like this for example:

[{
        "id" : "50",
        "family" : "Portulacaceae "
    }, {
        "id" : "76",
        "family" : "Styracaceae "
    }, {
        "id" : "137",
        "family" : "Dipsacaceae"
    }
]

URL called with ajax in this case is: http://localhost/webpage/json_family.php?term=acac&_=1417999511783 but I can't get that results in select2 input, console says:

Uncaught TypeError: Cannot read property 'length' of undefined

Here is code:
html

<input type="hidden" id="select2_family" name="term" style="width:30%" />

js

$("#select2_family").select2({
  minimumInputLength: 3,
  ajax: {
   url: "json_family.php",
   dataType: 'json',
   data: function (term) {
       return {
         term: term,
       };
   },
   results: function (data) {
     return { results: data.results };
   }

  }
});

php

$myArray = array();
if ($result = $mysqli->query("SELECT id,family FROM family WHERE family LIKE '%$term%'")) {
    $tempArray = array();
    while($row = $result->fetch_object()) {
            $tempArray = $row;
            array_push($myArray, $tempArray);
        }
    echo json_encode($myArray);
}

Is there error in code?

Hesperides answered 8/12, 2014 at 1:6 Comment(1)
try my updated php. not familiar enough with the plugin to whip right to the issue, but I've skimmed some of the docs. hopefully you'll get this working soonShipmaster
I
8

Ok, i have your example working on my test server, please do the following

change your query to this, changed a few names for readability but should be the same functionality, important part is addition of "AS TEXT" in query

$query = $mysqli->query("SELECT id, family AS text FROM family WHERE family LIKE '%$term%'"));
    while ($row = mysql_fetch_assoc($query)) {
           $return[] = $row;
         }

    echo json_encode($return);

second, it looks like you are trying to call a property from the json response called "results"

if that was the case your json should look like this, note that family is now text due to the change above:

{
"results":
[
    {
        "id": "50",
        "text": "Portulacaceae "
    },
    {
        "id": "76",
        "text": "Styracaceae "
    },
    {
        "id": "137",
        "text": "Dipsacaceae"
    }
]
}

But your php does not create the property results, so change your results function to remove the .results property call

   results: function (data) {
     return { results: data };
   }

final code i used (note i did not escape/sanitize the $_GET[term] or bind it to the query, recommend you do so ) if you are still having issues i can send you a link to my site example

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script>
</head>
<script>
$(document).ready(function () {

$("#select2_family").select2({
  minimumInputLength: 3,
  ajax: {
   url: "select2.php",
   dataType: 'json',
   data: function (term) {
       return {
         term: term,
       };
   },
   results: function (data) {
     return { results: data };
   }
  }
});

});
</script>

<input type="hidden" id="select2_family" name="term" style="width:30%" />

</html>

php

<?

/*** connection strings ***/

// get the database singleton instance
$yog = MySqlDatabase::getInstance();

// connect
try {
    $yog->connect($host, $user, $password, $db_name);
}
catch (Exception $e) {
    die($e->getMessage());
}

$term = $_GET['term'];

if (!$term){
$sub = $yog->query("SELECT id, family AS text FROM family");
} else {
$sub = $yog->query("SELECT id, family AS text FROM family where family like '%$term%'");
}

while ($row = mysql_fetch_assoc($sub)) {
       $return[] = $row;
     }

echo json_encode($return);

?>
Inlet answered 9/12, 2014 at 15:12 Comment(0)
S
1

Note: just a stab at it. Just what stuck out.

Your json has no property results, so try.

$("#select2_family").select2({
  minimumInputLength: 3,
  ajax: {
   url: "json_family.php",
   dataType: 'json',
   data: function (term) {
       return {
         term: term,
       };
   },
   results: function (data) {

     // CHANGED
     return { results: data };

   }

  }
});

changed the query -- see if this helps

$myArray = array();

// here
if ($result = $mysqli->query("SELECT id, family AS text FROM family WHERE family LIKE '%$term%'")) {
    $tempArray = array();
    while($row = $result->fetch_object()) {
            $tempArray = $row;
            array_push($myArray, $tempArray);
        }
    echo json_encode($myArray);
}
Shipmaster answered 8/12, 2014 at 1:12 Comment(1)
I get same error as I commented in above answer. Old one doesn't show up anymore but this 'toUpperCase' is shown and no data againHesperides
M
1

you need to define the text property on the results

and you might need to add formatResult and formatSelection

$("#select2_family").select2({
    minimumInputLength: 3,
    ajax: {
        url: "json_family.php",
        dataType: 'json',
        data: function (term) {
            return {
                term: term,
            };
        },
        results: function (data) {return { results: data, text: 'family'}; },
        formatResult: function(item) { return item.family; }, 
        formatSelection: function(item) { return item.family; }
    }
});
Midis answered 8/12, 2014 at 1:13 Comment(1)
Thanks, but when I do that new error is shown: Cannot read property 'toUpperCase' of undefinedHesperides

© 2022 - 2024 — McMap. All rights reserved.