Using PHP variables in a Javascript function

tommyp's Avatar, Join Date: Dec 2009
Newbie Member
I am trying to add a PHP variable $i, into a form element using a Javascript function, however this doesnt seem to be working at all, does anyone have any ideas why this may be? I am a novice coder so it may be something obvious. Any help please?

My code is:
HTML Code:
        <script type="text/javascript"> 
        function addvote() {
        var f = document.getElementById('vote');
        var entry_num = document.getElementById('entry_num')
        alert("document.write(entry_num)";
        document.forms.vote.entry_num.value=("<?php echo $i; ?>");
            if (f.entry_num.value!="")    {
            alert ("submitting vote");
                f.submit();
                                        }
                    else{
                        alert("error")
                        }
                           }
        </script>
Thanks
0
venami's Avatar, Join Date: Dec 2008
Ambitious contributor
Instead do like this:

PHP Code:
<?php
print "<script type=\"text/javascript\">\n";
print 
"function addvote() {\n";
print 
"var f = document.getElementById('vote');\n";
print 
"var entry_num = document.getElementById('entry_num')\n";
print 
"alert(\"document.write(entry_num)\";\n";
print 
"document.forms.vote.entry_num.value=(" $i ");\n";
print 
"if (f.entry_num.value!=\"\") {\n";
print 
"alert (\"submitting vote\");\n";
print 
"f.submit();\n";
print 
"}\n";
print 
"else{\n";
print 
"alert(\"error\")\n";
print 
"}\n";
print 
"}\n";
print 
"</script>\n";
?>
This must work now.