开发者

Calling a function from a PHP file to another PHP file?

开发者 https://www.devze.com 2023-04-10 11:45 出处:网络
I created a file called \"page.php\" with the below code. <!DOCTYPEHTML> <html> <body>

I created a file called "page.php" with the below code.

<!DOCTYPE  HTML>
<html>
    <body>
        <?php
            require 'form.php';
        ?>
        <a href="#" onclick="call_popup('form_container')">Click this link!</a>
   </body>
</html>

And I created another file "form.php" with the below code:

<script type="text/javascript">
    function call_popup (container_id) {
        var id= document.getElementById(container_id);
        alert(id);
    }
</script>开发者_运维百科
<div id="form_container">
    <form>
        <input type="text" />
        <input type="button" value="submit" />
    </form>
</div>

I am trying to call the "call_popup(container_id)" function in "page.php" which is defined in "form.php". When I click the "Click this link!" of the anchor tag it gives an error saying call_popup('form_container') not found!

Where did I go wrong?


Place your JavaScript code in a different file - for example file.js.

Include this file in all HTML files you wish to use your code in, in the head section:

<!DOCTYPE  HTML>
<html>
    <head>
        <script type="text/javascript" src="file.js"></script>
    <head>
    <body>
        <a href="#" onclick="call_popup('form_container')">Click this link!</a>
    </body>
</html>

It's better practice to separate client-side code (JavaScript) from server-side code (PHP).


You need to add this in the beginning of "page.php":

require_once("form.php");

But I am not sure that works with JavaScript functions..

Try create a JavaScript file, "file.js", and reference it in two PHP files:

<script src="file.js" type="text/javascript" />


I just tested your setup on my local XAMPP and it works (though it's not the best practice to mix JavaScript and HTML code). Are you sure the "require" call works? Do you see the form defined in "form.php" in your browser?

Maybe you just get the path to "form.php" wrong and have PHP error messages disabled on the server (not uncommon in a production environment). In that case PHP would die due to a missing file but won't throw any message that something went wrong...


Instead of using

require 'form.php';

inside the php tags use

include ()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号