Search the Community
Showing results for tags 'php jquery typeahead mysql'.
-
Im trying to make an input autocomplete(typeahead) that gets a value based from the query returned by the mysql query. What I would like to happen is to store the value of the returned row in a hidden field such as data-image so I could then use jquery to get the value of that hidden field and show a different image each time a value is selected from typeahead. I have already got as far as setting up typeahead with the database query, that works fine. Heres what I have: <?php $conn = new mysqli('localhost', 'root', '', 'fut_players') or die ('Cannot connect to db'); $result = $conn->query("SELECT player_image FROM player_info"); while ($row = $result->fetch_assoc()) { unset($player_image); $player_image = $row['player_image']; } echo "<input type='text' name='image' id='test' data-image='". $player_image ."' class='player_search' placeholder='players name'></input>"; ?> msql.php <?php $con = new mysqli("localhost","root","","fut_players"); $query = $_REQUEST['query']; $result = $con->query("SELECT id, player_name, player_image FROM player_info WHERE id LIKE '%{$query}%' OR player_name LIKE '%{$query}%'"); while ($row = $result->fetch_object()){ $user_arr[] = $row->id; $user_arr2[] = $row->player_image; $user_arr3[] = $row->player_name; } $result->close(); echo json_encode($user_arr3); ?> typeahead JQuery $(document).ready(function() { $('input.player_search').typeahead({ name: 'player_name', remote: 'mysql.php?query=%QUERY', }); }) Then I output the image: $('#test').on('change',function(e){ var img_url2 = $(this).data('image'); $('.player-img>img').remove(); $(".player-img").append("<img src='"+ img_url2 +"'>"); }); What currently happens is, on page load the value of player_image is added to data-image, even before anything is typed into the input field, it adds the very first row from the database and when a new item from the dropdown is selected a new value does not get added to data-image. I would like it not to query the db until a selection is made, then when a selection is made it adds the correct value to data-image