Passing values from PHP

A

anush

In a javascript file, I have to pass PHP values to the innerHTML. Can
anybody tell how I could do it.
 
D

David Dorward

anush said:
In a javascript file, I have to pass PHP values to the innerHTML. Can
anybody tell how I could do it.

innerHTML = "<?php echo $escapedToBeSafeForJSValue; ?>";
 
L

liamgegan

innerHTML = "<?php echo $escapedToBeSafeForJSValue; ?>";

That may be a little ambiguous though - as innerHTML is a property of
DOM element nodes. Maybe:

html_value1 = "<?php echo $escapedToBeSafeForJSValue; ?>";
.. . .
your_element.innerHTML=html_value1;

And of course, make sure you've had PHP escape the value properly (as
implied by David).
 
T

Thomas 'PointedEars' Lahn

anush said:
In a javascript file, I have to pass PHP values to the innerHTML. Can
anybody tell how I could do it.
innerHTML = "<?php echo $escapedToBeSafeForJSValue; ?>";
[...]

That may be a little ambiguous though - as innerHTML is a property of
DOM element nodes.

I am sure that was meant.
Maybe:

html_value1 = "<?php echo $escapedToBeSafeForJSValue; ?>";

Always declare your identifiers:

var html_value1 = ...
. . .
your_element.innerHTML=html_value1;

There is little reason for another variable here:

your_element.innerHTML = said:
And of course, make sure you've had PHP escape the value properly (as
implied by David).

Full ACK. http://php.net/addslashes


PointedEars
 
L

liamgegan

Always declare your identifiers:

var html_value1 = ...

Good point.
There is little reason for another variable here:

your_element.innerHTML = "<?php echo $escapedToBeSafeForJSValue; ?>";

Unless you wanted to pre-populate a variable for insertion at a later
point (an assumption)
 
J

Jeremy

That may be a little ambiguous though - as innerHTML is a property of
DOM element nodes. Maybe:

html_value1 = "<?php echo $escapedToBeSafeForJSValue; ?>";
. . .
your_element.innerHTML=html_value1;

A tip: I like to use json_encode for this:

var value = (<?php echo json_encode($variable); ?>);

If it's a string, it will automatically be escaped properly and
surrounded with quotes. But you can also pass numeric data, arrays, and
anonymous objects in this fashion, which is pretty convenient.

json_encode/decode is included with PHP >= 5.2.

Jeremy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,373
Latest member
Desiree036

Latest Threads

Top