Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Apr 2011
    Posts
    92
    Thanks
    26
    Thanked 0 Times in 0 Posts

    Using jquery autocomplete with a php array

    I have the following array:

    Code:
    $given_themes = array("ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme");
    I want to use these items in the following autocomplete script, but it is not working... How do I get it to recognize the array values? I am sure it has something to do with how I call the variable $given_themes...

    Code:
    <script>
    $(function() {
    var availableTags = [ <?php $given_themes; ?>];
    	$( "#tags" ).autocomplete({
    	source: availableTags
    	});
    });
    </script>
    
    <input name="theme" type="text" id="tags" value="<?php print "$theme"; ?>"/>

  • #2
    Regular Coder
    Join Date
    Jan 2008
    Location
    Geneva, Switzerland
    Posts
    413
    Thanks
    12
    Thanked 29 Times in 29 Posts
    You can't do that. You need to do an AJAX call to a PHP page that would generate this array. So you need 2 separate pages. Here is an example on how you can do that.

    The HTML / Javascript page:
    Code:
    <html>
        <head>
            <title>jQuery UI autocomplete</title>
    
            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
        </head>
    
        <body>
    
            <script type="text/javascript">
    
                $.getJSON("test.php", function(data) {
    
                    $( "#tags" ).autocomplete({
                        source: data
                    });
                });
    
            </script>
    
            <input id="tags" />
    
        </body>
    </html>
    The PHP page (test.php):
    PHP Code:
    <?php
    echo json_encode(array("ActionScript""AppleScript""Asp""BASIC""C""C++""Clojure""COBOL""ColdFusion""Erlang""Fortran""Groovy""Haskell""Java""JavaScript""Lisp""Perl""PHP""Python""Ruby""Scala""Scheme"));
    ?>
    This is a way... using some JSON output and the built-in getJSON jQuery function.

    But the autocomplete function has a built-in way to query a php page. Please check this: http://jqueryui.com/demos/autocomplete/#remote
    Chuck Norris counted to infinity.
    Twice.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •