user1650559
user1650559

Reputation: 13

jQuery Autocomplete: Uncaught TypeError: Cannot read property 'length' of null

My first time using JQuery. Trying to use Autocomplete, and keep getting the error above. I've tested the MySQL queries and they all work. If I use the same code below but called from a webpage without the Autocomplete code, the JSON looks well-formed. Thanks for any guidance you can provide.

<?php
$docname=$_POST['docselect'];
$surname=$_POST['lastname1'];
if (isset($_POST['lastname1'])){
    $return_arr = array();
try {
    $dbc=mysqli_connect('localhost','gotlibc_testuser','**passwordgoeshere**','gotlibc_robo2')     or die("Error connecting to MySQL server.");

$query="SELECT PT_ID, surname, firstname, jnum FROM patients WHERE surname LIKE '$surname%' ORDER BY surname";

$result=mysqli_query($dbc,$query) or die('Error querying database.');

$row=array();
while($Xrow = mysqli_fetch_array($result)) {
   $row['label']="{$Xrow['surname']},{$Xrow['firstname']},{$Xrow['jnum']}";
   $row['value']=$Xrow['PT_ID'];
  $return_arr[]=$row;
}
}
// end try
catch(Exception $e ) {
echo "<script type='text/javascript'> alert('Hi'); </script>";
printf("catch activated"); 
echo $e->errorMessage();
}
echo json_encode($return_arr);
mysqli_close($dbc);
}
?>

Here's the relevant snippets of the calling web page

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(document).ready(function(){
        $( "#lastname1" ).autocomplete({
              source: "pt_autoshow1.php", minLength: 1
});
});
</script>

<h2>Patient Information:</h2>
<br>
<form id="surnamepicker" action="#" method="post"> or Last name: <input name="lastname1" id="lastname1" type="text">
    <div class="rage_button_781076"> <a href="">New Patient</a> </div>
 with Dr.
  <select name="docname">
    <option value="2">Doctor A</option>
    <option value="1">Doctor B</option>
    <option value="3">Doctor C</option>
  </select></form>

Upvotes: 0

Views: 7844

Answers (1)

shyam.y
shyam.y

Reputation: 1491

its working fine for me php function will return the rows/No Results as response

    public function shamsearchJSON ()
    {
     $search = $this->input->post('search');

    $query = $this->user_model->getmessages($search);

        if(!empty($query)){
        echo json_encode(array('responses'=> $query));
        }
        else{
        echo json_encode(array('responses'=> 'No Results'));
        }
}

javascript code

    $( "#search-inbox" ).autocomplete({
              minLength: 2,
              source: function( request, response ) {
                //  $.getJSON( "<?php echo base_url(); ?>index.php/user/shamsearchJSON?search="+request.term,response );

                        $.ajax({
                          url: "<?php echo base_url(); ?>index.php/user/shamsearchJSON",
                          data: {"search": request.term},
                          type:"POST",
                          success: function( data ) {

                           var parsed = JSON.parse(data);

                           if(parsed.responses == "No Results")
                           {
                           alert("no results::");
                           var newArray = new Array(1);
                           var newObject = {
                                        sub: "No Results",
                                        id: 0
                                    };

                           }
                           else{
                                var newArray = new Array(parsed.length);
                                var i = 0;
                                parsed.responses.forEach(function (entry) {
                                    var newObject = {
                                        sub: entry.subject,
                                        id: entry.mID
                                    };
                                    newArray[i] = newObject;
                                    i++;
                                });

                            }
                            response(newArray);
                         },
                          error:function(){
                          alert("Please try again later");
                          }
                        });  

                },
              focus: function( event, ui ) {
                //$( "#search-inbox" ).val( ui.item.sub );
                return false;
              },
              select: function( event, ui ) {
              if(ui.item.id != 0){
                $( "#search-inbox" ).val( ui.item.sub );
                openInboxMessage(ui.item.id);
                }
                else
                {

                }
                return false;
              }
            }).data( "ui-autocomplete" )._renderItem = function( ul, item ){
              return $( "<li>" ).append("<a>" + item.sub +"</a>" ).appendTo(ul);
            };

Upvotes: 1

Related Questions