0

After hours of frustration, I finally found the line of code that has been causing an error, but now I need to know why.

jQuery was throwing this error: Uncaught Error: Syntax error, unrecognized expression: .

I've researched it and found that this is a Sizzle error that occurs when jQuery cannot find the selector that is referenced. As was suggested in other questions on SO, this was not actually an error in my jQuery code, it was elsewhere.

I was defining a variable to use as a target element to load content, and was using PHP to dynamically define the variable, like so:

var $container = $(".<? echo $target ?>");

This did not work, as the . is flagged as an unrecognized expression. However, replacing the PHP variable with a static string works fine:

var $container = $(".target");

This was so hard for me to find because I couldn't pinpoint the line that was throwing the error, and in the source from the browser, the initial line above looks just like the second line.

Why does the first example not work? Does it have to do with order of execution? And, how can I use a dynamic variable as a selector?

3
  • Show us the generated source. Commented Feb 27, 2013 at 17:14
  • 1
    Are you sure $target has some value? Could it be empty? Commented Feb 27, 2013 at 17:16
  • The generated source is var $container = $(".target");, this is why I'm very confused. $target has a value, as the source is printing ".target". Commented Feb 27, 2013 at 17:19

3 Answers 3

2

you have to use

<?php echo $test; ?>

or the shortcut:

<?= $test ?>
Sign up to request clarification or add additional context in comments.

Comments

0

You can try trim($target) before doing this. If it works you probably have some unwanted spaces in that variable of yours.

Also consider using json_encode to pass variables from php to javascript. Like so:

var selector = <?php echo json_encode($target); ?>;
var $container = $(selector);

This will allow you to pass not only simple strings but more complex variable structures as well (and with encoding safety).

1 Comment

Thanks for the advice about json_encode; I'll be using that for now on.
0

Turns out the page I was loading wasn't having the variable $target passed to it. On the initial page, $target was initialized with a value, and thus the source output looked as specified in the question. However, the ajax call I was making to reload the page with new data was not passing the variable.

Comments

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.