views:

94

answers:

6

Hi,

I basically just want to append a javascript variable to an HTML div with JQuery. However I need to append some PHP code as a string, it doesn't need to execute it just needs to show up as a plain old string string.

The following code doesn't seem to append because I think it is still recognized as PHP syntax.

var script = '<?php wp_list_pages(); ?>';
divName.innerHTML = script;

Any help would be much appreciated.

+2  A: 

Wrap it in CODE tags, like this:

var script = '<code><?php wp_list_pages(); ?></code>';
RedFilter
+2  A: 

Try:

var script = '<?php echo '<?php wp_list_pages(); ?>'; ?>';

prodigitalson
People, I wouldn't be so quick to downvote this. The OPs descriptions allows the reading that this is exactly what he is looking for.
Gordon
+1  A: 

You probably should escape the "hot" HTML tokens in the PHP text:

div.innerHTML = script.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
Pointy
This also does the works, thanks.
Goldy
+3  A: 

Just a guess... replace the php brackets with HTML entities (&lt; and &gt;) so it will not be interpreted as PHP code (if you run the file containing the JS through PHP) nor as strange HTML code (the browser searches for brackets as html tags, remember...) by the browser.

Steffen Müller
Thanks this does the trick. Only problem now is I am going to use Adobe AIR to save the contents of that div as an actual PHP file, and therefore needs to execute in that file. Not sure what I am trying to achieve is actually possible. However your answer was useful. Thanks.
Goldy
@Goldy NO! Please see my answer.
Lucas Oman
+1  A: 

You need to simply escape the string with HTML entities (&lt; and &gt;)

IMPORTANT: I hope all you're doing here is trying to display the PHP code. Please don't try anything funky where PHP code is passed in a form's field back to the server and executed via eval() or somesuch. That would be an unimaginably terrible idea. Anytime you give the client access to code that will be executed on the server, you open yourself up to all kinds of exploits. Your server will be forfeit. Do not collect $200. Game over. Fail.

Lucas Oman
heheh, that's the first thing that crossed my mind reading this :)
Paolo
No need to worry, all I wanted to just show the code as text! Was not planning to try anything 'funky'. I am attempting to create a theme customizing tool with Adobe AIR.
Goldy
@Goldy Ok. You really had me worried for a moment. Even if you understand what a terrible idea this is, you'd be amazed how often people cook up awful schemes like this.
Lucas Oman
A: 

PHP is executed before the page is sent to the browser, so you can go to that page, open its source and see if in that line you see what you need to see, like:

var script = 'the content you expect to see';

if not, tell us what you see.

kemp