I am a newbie and have searched for the answer to my problem, but none of them seem to work, or I am so dumb I am doing it wrong....
The need seems simple.....
I would like to bring an array (would be happy with just a single variable) to javascript. But I can't get it done. Below is a simple portion of the code I am trying...any help would be appreciated.
<?$test='hello'?>
<script language="javascript" type="text/javascript">
var jstest='<?=$test?>';
document.write('jstest');
</script>
[RESOLVED] Getting PHP variable into javascript
Haha, sorry.
Your problem isn't in php. Your javascript is a bit tweaky.
This works for me:
<html>
<head>
<?$test='hello'?>
</HEAD>
<body>
<SCRIPT language="JavaScript">
var jstest="<?= $test ?>";
document.write(jstest);
</script>
</body>
</html>
document.write('jstest');
..should be
document.write(jstest);
'jstest' is a string but jstest is the variable that you defined earlier.
I apologize for the tweakniness however in the code below, ktest will print and jstest does not.
<?$test='hello';?>
<script language="javascript" type="text/javascript">
var jstest='<?=$test?>';
var ktest="jjjj";
document.write("var='"+jstest+"'");
document.write("var='"+ktest+"'");
</script>
Cahva - thanks for the additional answer, but I changed the above code to display according to your syntax (jstest) and it displays a blank - the var literal is there followed by nothing. Any ideas.
Bob
Hmm, weird. I get var='hello'var='jjjj' on IE, Firefox and NetScape using your same code.
<html>
<head>
<?$test='hello'?>
</HEAD>
<body>
<?$test='hello';?>
<script language="javascript" type="text/javascript">
var jstest='<?=$test?>';
var ktest="jjjj";
document.write("var='"+jstest+"'");
document.write("var='"+ktest+"'");
</script>
</body>
</html>
Perhaps the short_tag option is not enabled?
Either way, it's not a generally good coding practice to use; try using a full <?php echo $var; ?> syntax.
Brad - thank you very much that was it! Now, will an array work the same? Might you have an example of how to do that? Thanks for your help.