Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling JQuery autocomplete with PHP array

I'm a relative noob to JavaScript and JQuery, but I've been searching the web for hours to find an answer to this question. I'm trying to populate a JQuery autocomplete function using an array I've made in PHP. This is a snippet of the array:

<?php
    $arr = array(
        "Abaddon" => "/BlinkDaggerSounds/abad_blink_01.mp3",
        "Alchemist" => "/BlinkDaggerSounds/alch_blink_01.mp3",
        "Anti Mage" => "/BlinkDaggerSounds/anti_blink_01.mp3",
        "Ancient Apparition" => "/BlinkDaggerSounds/appa_blink_01.mp3",
        "Axe" => "/BlinkDaggerSounds/axe_blink_01.mp3", 
    );
?>

And here is the script I'm trying to run:

<script>
    $(function() {

        var availableTags = <?php echo json_encode($arr); ?>

        $( "#auto" ).autocomplete({
            source: availableTags;
        });

    });
</script>

And here is the form:

<form method="post" action="BlinkDaggerQuiz.php" class="answer_box">
    <p>Which hero is it?  <input type="text" id="auto" name="guess" /></p>
</form>

And my head tags:

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="BlinkDaggerQuiz.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>

I can't figure out what I'm missing; the autocomplete options will not show in the text box. I've also tried substituting implode() for the json_encode(), but got the same non-results.

like image 795
Mason Avatar asked Sep 27 '22 17:09

Mason


1 Answers

I believe your current code should be returning some syntax errors. Hit F12 and find out.

You appear to be trying to use the Autocomplete widget from jQuery UI. There is no autocomplete feature built into plain old jQuery so you will have to include jQuery UI as well.

This part is JavaScript:

$( "#auto" ).autocomplete({
    source: availableTags;
    });
});

This means availableTags needs to be a JavaScript array as well. The easiest syntax for JavaScript arrays is var myArray = ['a', 'b', 'c'];.

You need to output your PHP array into a JavaScript array which can be done with the implode function. If given an array, the implode function will join all values in that array. In your case you want the keys of the array to be in the array instead of the values. So you can use the array_keys function to retrieve all the keys in the given array. You will end up with:

var availableTags = [<?php echo '"' . implode ('","', array_keys ($arr)) . '"'; ?>];

When your page loads you should end up with a proper JavaScript array:

var availableTags = ["Abaddon","Alchemist", "Anti Mage", "Ancient Apparition", "Axe"];

To my knowledge there are no Dota heroes with double quotes in their names so using double quotes as strings should be fine..

like image 137
TreeTree Avatar answered Oct 04 '22 17:10

TreeTree