Given my html file, the console gives an error code:
Reference Error: loadData not defined.
Based from other answers I've rechecked mine where,
- My function is declared just before the
</body>, - I included the javascript library at the
<head></head>; - and even changed my
<input type= submitto<input type= button - and if it helped, I tried deleting my form tags where it is enclosed (but this is for another question regarding query strings).
Here's how it would look like now:
<head>
<script src = "//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
{%for document in documents %}
<li> {{document.filename}}
<input type="button" id="{{ document.id }}" onclick="loadData(this.id)" name = "load-data" value="Add to Layer"/>
</li>
{%endfor%}
<script type ="text/javascript">
function loadData(documentId){
$.ajax({
url:"/load",
data: {'documentId': documentId},
type: 'GET',
success: function(){
window.location.href = "http://127.0.0.1:8000/url/locations";
}
});
}
</script>
</body>
I can't seem to find an explanation why the function won't fire.
2 Answers 2
Here's the fix (as my friend explained):
I had to put my script up in the <head> tags.
Why? Because the document is already loaded before the script gets to be.
If I want to retain it at the bottom it had to look something like this:
$(document).ready(
$('input').onclick(function(){})
After putting it up the code works.
4 Comments
I've tested your html and everything seems to be working properly. The only error that I found was that $ajax is not a function. It is missing a dot $ajax => $.ajax
Try using:
function loadData(documentId){
$.ajax({
url:"/load",
data: {'documentId': documentId},
type: 'GET',
success: function(){
window.location.href = "http://127.0.0.1:8000/url/locations";
}
});
}
1 Comment
Explore related questions
See similar questions with these tags.
<script>tag doesn't close your javascript function."in the button'snameattribute. Your point 1 shouldn't matter because regardless of where the script is it will have been run by the time the user actually clicks on the buttons. Points 2-4 shouldn't matter at all as far as whether the function can be called from theonclick.