0

I have a php function that pull data from the database and return html code which is a code for a drop down menu. What I need to do is append this drop down menu to the div using jQuery. The problem that I am having is how can I assign the return value from php into a jQuery variable?

function returnUserNames(){
//open connection to the database

return 'this an html code that should be returned by this function';

}

I have tried the following but it is not working.

<script>
var menu = <?php echo returnUserNames() ?>;
$('#show_menu').append(menu);
</script>

Thanks

2
  • 1
    Put <?php echo returnUserNames() ?> in ". Commented Sep 9, 2013 at 20:05
  • I did add a quote but I get a "Uncaught SyntaxError: Unexpected string" error Commented Sep 9, 2013 at 20:11

2 Answers 2

4

Your PHP code is generating text that is going directly into a Javascript context, meaning that you have to generate VALID javascript code. As it stands now, your code will produce

var menu = this an html code that should be returned by this function;

which is an outright javascript syntax error. Never EVER directly output text from PHP into a javascript context like this. Always use json_encode() to ensure that whatever you're outputting becomes syntactically valid Javascript, e.g.:

var menu = <?php echo json_encode(returnUserNames()) ?>;
                      ^^^^^^^^^^^^

which will produce:

var menu = 'this an html code that should be returned by this function';

Note how the ' quotes were automatically added.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This was the solution :)
2

You have misspelt return and script.

var menu = <?php echo returnUserNames() ?>;

this whole php-script also needs to be enclosed in quotation marks:

var menu = "<?php echo returnUserNames() ?>";

And your jQuery script shouldn't run until the page is loaded, and #show_menu is available.

2 Comments

Thanks for poiting out the typos. Those are typos in this page and not in the actual script. The error that i get is "Uncaught SyntaxError: Unexpected string"
Please always copy and paste the real script, don't attempt to re-type it. As you have seen, you can introduce errors that aren't relevant to the question. Marc recommends another approach that wouldn't require the quotes.

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.