¿Hacer que el valor de retorno de una función de PHP sea igual a una variable de javascript?

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>

Muchas Gracias

preguntado el 09 de septiembre de 13 a las 21:09

poner <?php echo returnUserNames() ?> in ". -

I did add a quote but I get a "Uncaught SyntaxError: Unexpected string" error -

2 Respuestas

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 NUNCA 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()) ?>;
                      ^^^^^^^^^^^^

que producirá:

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

Tenga en cuenta cómo el ' quotes were automatically added.

Respondido el 09 de Septiembre de 13 a las 21:09

Thank you. This was the solution :) - jaylen

Tienes mal escrito retorno y guión.

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 está disponible.

Respondido el 09 de Septiembre de 13 a las 21:09

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" - jaylen

Please always copy and paste the reales 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. - Andy G

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.