1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Using PHP variables in a Javascript function

Discussion in 'Programming' started by tommyp, Dec 16, 2009.

  1. tommyp

    tommyp New Member

    Joined:
    Dec 9, 2009
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    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:
            <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
     
  2. venami

    venami New Member

    Joined:
    Dec 26, 2008
    Messages:
    195
    Likes Received:
    10
    Trophy Points:
    0
    Occupation:
    Software Professional
    Location:
    India, Tamil Nadu, Cuddalore
    Home Page:
    Instead do like this:

    PHP:
    <?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.
     
    shabbir likes this.

Share This Page