html javascript - onclick() reference error: function not defined

15,211

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.

Share:
15,211
Reiion
Author by

Reiion

Updated on June 04, 2022

Comments

  • Reiion
    Reiion almost 2 years

    Given my html file, the console gives an error code:

    Reference Error: loadData not defined.

    Based from other answers I've rechecked mine where,

    1. My function is declared just before the </body>,
    2. I included the javascript library at the <head></head> ;
    3. and even changed my <input type= submit to <input type= button
    4. 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.

  • Reiion
    Reiion over 7 years
    sorry I had to edit that again in the post. my code has the dot in ajax but still doesn't work :(
  • nnnnnn
    nnnnnn over 7 years
    That explanation doesn't really make sense for code called by a click event (unless the page loads so slowly that the user sees the control and clicks it before the rest of the page loads). For the code shown it shouldn't make any difference: jsfiddle.net/asa2rfeh
  • Reiion
    Reiion over 7 years
    @nnnnnn actually you are right I also tried it from a blank html just to test. It also weirded me out... it just kept on saying the Reference Error: loadData is not defined. Although the fix worked, I really want an explanation why in my case it wouldn't.
  • Craftein
    Craftein over 7 years
    @Reiion assuming you have more codes than what you've posted, you probably have some javascript error before where the function is defined.
  • Reiion
    Reiion over 7 years
    @Craftein yeah most probably but I can't really explain why it won't work at the bottom. The browser console tells nothing of any error too