August 17, 2013

PHP not working in javascript function

Ceelos’s Question:

Trying out PHP for the first time and I’m really stumped on this. It might be something obvious, but why isn’t my php inside the function checkinfo() working? The alert works fine. Here’s the code

<head>
    <script type="text/javascript">

            function checkinfo() {
                alert("hi");
                <?php
                echo 'hi';
                ?>
            };

        </script>

    </head>
    <body>
        <form id = "form" align = "center">

            <div id = "index">

                <div id = "unandpw">
                    Username:
                    <input type="text">
                    <br>
                    Password:
                    <input type ="password" >
                </div>
                <!-- end unandpw -->

                <div id = "buttons">
                    <button type = "button" onclick = "checkinfo()">
                        Login
                    </button>
                    <button type = "button" onclick = "register();">
                        Register
                    </button>
                </div>
                <!-- end buttons -->

            </div>
            <!--index end -->

        </form>
    </body>
</html>

It gives error, because when the rendered your script becomes this:

function checkinfo() {
   alert("hi");
   hi
};

Which is an incorrect code. You may be trying to do:

alert("<?php echo 'hi'; ?>");

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!