user360330
user360330

Reputation:

call function from external js (php) file

I have a file where I keep all scripts so my pages wouldn't get messy (I have php file which generates required javascript). My includes basically look like this:

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="script.php"></script>
</head>
<body>
    <input type="button" onClick="return blah();" />
</body>
</html>

script.php

<?php
    header("content-type: application/x-javascript");   
?>

    function blah()
    {
        alert("blah");
    }

    $(document).ready(function() 
    {});

In script.php there's jquery wrapper $(document).ready where I keep all jquery related stuff. The funny thing is, when I put function blah() inside this wrapper I get "blah is not defined" error, but when I put it outside - works perfectly. So, what could be the problem?

Upvotes: 1

Views: 1581

Answers (2)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146460

If you do this:

function(){
    var foo = function(){
    }
    // Other stuff
}

... you are defining a private function that only exists inside the external function. If you want it global, you must either define it outside:

var foo = function(){
}
jQuery.ready(
    function(){
        // Other stuff
    }
);

... or append it to a global object, such as window:

jQuery.ready(
    function(){
        window.foo = function(){
        }
        // Other stuff
    }
);

It's worth noting that using external files does not change this.

Answer to updated question:

blah() is not defined. Your function is called checkField().

Upvotes: 0

Lloyd
Lloyd

Reputation: 29668

Surely that's a simple scoping issue?

$(function(){

    window.blah = function() {

    };

});

Upvotes: 1

Related Questions