1

Hello here is my problem.

I have an autocomplete input that retrive data from my database that shows me an image and a text. What I want to do is add another text next to it but from another field. But when I try it doesn't find my image anymore.

Here is my code :

PHP FILE


  <input type="text" name="text" id="text" autocomplete="off"><br />

  <input type="submit" name="submit" class="button"><br /><br />

</form>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>

<script type="text/javascript">

  $(function(){

    $('#ref').autocomplete({

      source: 'autocomplete.php'

    }).data("ui-autocomplete")._renderItem = function (ul, item) {
      return $("<li><div><img src='img/" + item.value + "' /><span>" + item.value + "</span></div></li>").appendTo(ul);
    };

  });
</script>

autocomplete.php


  require('db.php');

  $term = $_GET['term'];


  $q = $db -> prepare('SELECT data1,data2 FROM table WHERE data1 LIKE :term');

  $q -> execute(array('term' => '%'.$term.'%'));


  $array = array();

  while ($data = $q -> fetch()) {

    array_push($array, $data['data1']. ":".$data['data2']);

  }


  echo json_encode($array);

?>

So to be clear this is how i'd like it to be shown in my input :

MYIMG DATA1 : DATA2

Sorry if I'm not being clear enough.

Thanks for your help.

6
  • Do you really have <?php right before you write the HTML form? That should throw some serious errors since the PHP parser will parse it as PHP, which it isn't. Commented Dec 10, 2019 at 15:09
  • Your image file name is same as data1, right? so now your filename is returning as "data1:data2" which is not the file name. Quick and dirty solution would be to split your item.value on colon : and use index 0 as image source. CORRECT way is to return proper JSON with data1 and data2 as separate properties and format them on client side.
    – Nawed Khan
    Commented Dec 10, 2019 at 15:35
  • No sorry i don't have it
    – mslol
    Commented Dec 10, 2019 at 15:36
  • Change the code to what you have then, please.
    – Refilon
    Commented Dec 10, 2019 at 15:40
  • The problem is that i don't know much about javascript and JSON i found the code online and it worked. Is it correct if i do it like this ? while($data = $q->fetch()) { array_push($array, $data['data1']); array_push($array2, $data['data2']); } echo json_encode($array2);
    – mslol
    Commented Dec 10, 2019 at 15:42

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.