0

I've simplified the problem down as much as possible, I feel like this should work. The below script controls the autocomplete function and works as expected (if a user types 't', 'test' appears as a suggested input).

<script type="text/javascript">
$(function() {
    var availableClients = ['test'];
    $("#addClient").autocomplete({
        source: availableClients,
    });
});
</script>

However, if I set a PHP variable $test = "'test'" and replace 'test' in the original script with <?php echo $test; ?> the autocomplete script no longer works. Is there another way I can use a PHP variable as the autocomplete source or am I missing something?

EDIT: Here is the script with the PHP in it.

<script type="text/javascript">
$(function() {
    var availableClients = [<?php echo $test; ?>];
    $("#addClient").autocomplete({
        source: availableClients,
    });
});
</script>

And the only relevant PHP code is this.

$test = "'test'";
3
  • Nothing wrong with this, you probably need to show us more code. Commented Dec 1, 2012 at 22:38
  • Please include the full PHP code where you're trying to insert $test as well as the output it generates. Commented Dec 1, 2012 at 22:40
  • Added all relevant code. Commented Dec 1, 2012 at 22:57

1 Answer 1

1

The issue is probably that you aren't including the quotes when echoing the value of the variable. Try this:

var availableClients = ['<?php echo $test; ?>'];

As it turns out, the issue was actually that you were not defining $test before you were echoing it. This:

$test = "'test'";

needs to occur before this:

<script type="text/javascript">
$(function() {
    var availableClients = [<?php echo $test; ?>];
    $("#addClient").autocomplete({
        source: availableClients,
    });
});
</script>
Sign up to request clarification or add additional context in comments.

9 Comments

Or of course <?=$test?> if you have short open tags enabled. Make sure that the js file ends with .php or is interpreted as a PHP file so it executes the PHP.
@h2ooooooo Yeah, but those are deprecated if I remember correctly.
(I can't @ you for some reason) According to my link: This directive also affected the shorthand <?= before PHP 5.4.0, which is identical to <? echo. Use of this shortcut required short_open_tag to be on. Since PHP 5.4.0, <?= is always available. - so it doesn't seem like it.
Asad - hard to tell but the $test variable is 'test', the quotes are already there.
easy to look in source view in browser or in console and see what actually arrives at page
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.