Layla Wang
Layla Wang

Reputation: 65

Why is $("#tags").autocomplete not working with data from PHP?

  <script>
  <?php
    mysql_connect('127.0.0.1', 'root', '') or die(mysql_error());
    mysql_select_db("Project_Part1")or die("cannot select DB");
    $sqlActivity = "SELECT aname FROM Activity";
    $resultActivity=mysql_query($sqlActivity);
    $aname = array();
    while ($row = mysql_fetch_array($resultActivity)) {
      $aname[] = $row;
   }    
  ?>
  $(function() {
        var availableTags =[ "<?php echo implode('","',$aname);?>" ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  });
  </script>
<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags" />
</div>

Not sure why var availableTags =[ "<?php echo implode('","',$aname);?>" ]; is not working for the autocomplete. When I use var availableTags = [ "Rock climbing","Fishing","Kayaking","Underwater bungee jumping" ]; It is fine.

I'm new on PHP. Can anyone help me on this?

Upvotes: 0

Views: 575

Answers (1)

Jason
Jason

Reputation: 15335

Try:

<?php
    $DBi   = mysqli_connect($hostname, $user, $password, $database);
    $aname = array();

    $sqlActivity = "SELECT `aname` FROM `Activity`";
    $resultActivity = mysqli_query($DBi, $sqlActivity);   //Dump mysql_query for 
                                                          //mysqli_query and don't 
                                                          //forget the connection bit
    while ($row = mysqli_fetch_array($resultActivity)) {
        $aname[] = $row;
    };    
?>

<script>
    $(function() {
        var availableTags =[ "<?php echo implode('","',$aname);?>" ];
        $("#tags").autocomplete({
            source: availableTags
        });
    });
</script>

<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags" />
</div>

It looks like you are missing <?php right after your <script> tag. I moved the PHP SQL bit outside of your <script> tag (which should not matter but does help to keep things a little easier to read in my mind)

While you are at it, stop using mysql_ and switch over to mysqli_ functions as the former are deprecated

Upvotes: 1

Related Questions