0

I am getting this error validate_allocation is not defined when trying to execute a function from a static file. Any idea why?

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="static/main.js"></script>
<script>
validate_allocation();
</script>

main.js

$(function() {
    alert('test'); // I can see this, so the file is imported for sure
    function validate_allocation(){
        alert('test');
    }
}); 
anvd
  • 3,997
  • 19
  • 65
  • 126
  • because validate_allocation is not global, you defined it in another function (the ready callback) so it is not accessible outside that – Patrick Evans Jun 29 '17 at 03:01
  • `validate_allocation` is a local declaration that only exists within `$(function() { ... })`. Another ` – Jonathan Lonowski Jun 29 '17 at 03:02
  • @JonathanLonowski my real problem is that I need to use in recaptcha callback a function from jquery context. Apparently this is problematic. https://stackoverflow.com/questions/35614606/google-recaptcha-data-callback-not-working – anvd Jun 29 '17 at 03:10
  • @PatrickEvans please see my comment above. – anvd Jun 29 '17 at 03:14
  • That question's solution is the same, move the function definition to be defined in global scope. What do you mean by "from jQuery context"? – Patrick Evans Jun 29 '17 at 04:25

2 Answers2

1

The purpose of $(function() { ... }); is to run the code inside once the page has finished loading. As others have said, you're defining a function not only after the page has finished loading (and therefore after the call is made in your HTML file), but it is also limited to the scope of that block. It can safely be moved out of the block:

// Declare function at the root of the document and make it accessible to the HTML page
function validate_allocation(){
    alert('test');
}

// Actions to perform when the page has completed loading
$(function() {
    alert('test'); // I can see this, so the file is imported for sure
}); 
Eraph
  • 1,019
  • 1
  • 10
  • 21
0

Remove the Validate_allocation function from jquery onload function. Since you are writing in that function it will be scoped to that function only.

function validate_allocation(){
        alert('test');
    }
$(function() {
    alert('test'); // I can see this, so the file is imported for sure    
}); 

This will make the function globally accessible

praveen
  • 489
  • 6
  • 12