Jump to content

PHP variable as DOM proxy ?


brucemand

Recommended Posts

a bit unsure where to post this thread; being DOM-related i thought on the JS board, but then i think it's more of a PHP issue.i am reading in a PHP data array and assigning it to a display element, the default being the 1st index of said array, like so;

echo '<input type="text" id="display" readonly="readonly" value="'.$stats[0].'" />';

next; based on a <select> element, i have a JS function changing that 'display', except i'm stuck as to how to read the PHP variable $stats[n] into the DOM.i got as far as;

var display=document.getElementById('display');var index=(selectElement).selectedIndex;

but then it gets tricky (!!) with;

display.value='<?php echo $stats."[";?>'+index+'<?php echo "]";?>';

is this at all possible, or do i have to use a hidden <input> to store each $stats[n] ?

Link to comment
Share on other sites

Just remember that all the PHP is parsed before any Javascript runs.You could simplify this line to:

display.value='<?php echo $stats; ?>[' + index + ']';

Given that $stats is an array, the Javascript will end up executing this code:

display.value='Array[' + index + ']';

Link to comment
Share on other sites

Just remember that all the PHP is parsed before any Javascript runs.You could simplify this line to:
display.value='<?php echo $stats; ?>[' + index + ']';

Given that $stats is an array, the Javascript will end up executing this code:

display.value='Array[' + index + ']';

hmm... not serving the answer on a plate, eh ? :)so... meaning that... once we're in JS (client-side), that means PHP has left the building.therefore, it's "not possible" NO! - is this where AJAX comes in with the HTTP.Request object ?otherwise, the answer is use a <input type="hidden" />, yes ? NO!!EDIT: answering myself in that last line you showed, Array is the PHP keyword(?) which to JS means undeclared (in JS) array, right ?so i still have to declare the variable in JS - am i on the right track ?
Link to comment
Share on other sites

GOT it ! :) with a lot of skipping in & out of PHP !

<?php	$stats=array(100,200,300);	?><script type="text/javascript"><?php	$statsLIT="(";		foreach($stats as $stat)	$statsLIT.= $stat.",";	$Jstats=substr($statsLIT, 0, -1).")";?>	Jstats=new Array<?php echo $Jstats; ?>;	</script><?php...continues...?>

no DOM element <input type="hidden" /> required !!

Link to comment
Share on other sites

That works, but watch out. It works only for numbers. If you have strings you'll have to make sure that quotes are printed around them when sending them to Javascript. You can use is_string() to test whether a value is a string.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...