Link to home
Start Free TrialLog in
Avatar of Crazy Horse
Crazy HorseFlag for South Africa

asked on

uncaught reference error for defined jquery function

I have a functions.js file with a function in it:

function list_cat() {

    $.ajax({

            url: 'functions/list-categories.php',
            type: 'POST',
            dataType: 'json'
        })
        .done(function(data) {
            $.each(data, function(item) {
                var cat_options = "<option value='" + data[item].id + "'>" + data[item].cat_name + "</option>";
                $("#n_category").append(cat_options);
            });
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus + ': ' + errorThrown);
            console.warn(jqXHR.responseText);
        });
}

Open in new window


I am trying to call it like this:

<script type="text/javascript">
	list_cat();
</script>

Open in new window


When I try to just call this function on another page I get the error:

 Uncaught ReferenceError: list_cat is not defined
Avatar of HainKurt
HainKurt
Flag of Canada image

are you adding/referencing this js file on another page?

also, if you are adding, make sure that js comes before you call it...
Avatar of Crazy Horse

ASKER

I am including the js file like this and then only calling the function underneath this line.

<script src="functions.js"></script>
<script type="text/javascript">
	list_cat();
</script>

Open in new window

open it on chrome
press F12
check console errors...

probably you have syntax errors on js...
If I run the exact code in the page itself and don't call the function from a script.js file then it works perfectly. In other words if I put this at the bottom of the page:

$.ajax({

            url: 'functions/list-categories.php',
            type: 'POST',
            dataType: 'json'
        })
        .done(function(data) {
            $.each(data, function(item) {
                var cat_options = "<option value='" + data[item].id + "'>" + data[item].cat_name + "</option>";
                $("#n_category").append(cat_options);
            });
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus + ': ' + errorThrown);
            console.warn(jqXHR.responseText);
        });

Open in new window

Avatar of Steve Bink
When running javascript like this, it could be that the file you're depending on has not yet been received/parsed.  Since you're using jQuery, use something like this boilerplate:
(function($, document, window) {
  $(document).ready(function() {
    // Your code goes here
  });
)}(jQuery, document, window);

Open in new window

As always, make sure jQuery is one of the first files loaded.  It should at least be before any custom code like this.
Note: this is just a comment on your use of $.each()

The function works as follows
$.each(index, item)

You have used it the way you would use a for loop in other words using the index (first parameter) into the structure you are iterating over and not making use of the actual item that is passed into the function for you.

See my revisions in the code below.

This works for me
HTML
<select id="n_category"></select>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="t2575.functions.js"></script>
<script type="text/javascript">
	list_cat();
</script>

Open in new window

functions.js
function list_cat() {

    $.ajax({

            url: 't2575.php',
            type: 'POST',
            dataType: 'json'
        })
        .done(function(data) {
            // Note the changes here to use item.id instead of data[item].id
            $.each(data, function(index, item) {
                var cat_options = "<option value='" + item.id + "'>" + item.cat_name + "</option>";
                $("#n_category").append(cat_options);
            });
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus + ': ' + errorThrown);
            console.warn(jqXHR.responseText);
        });
}

Open in new window

PHP
[{
	"id": 1,
	"cat_name": "Option 1"
},{
	"id": 2,
	"cat_name": "Option 2"
},{
	"id": 3,
	"cat_name": "Option 3"
}]

Open in new window


Working sample here
Thanks everyone, going to try this out when I get in front of my development machine....
SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I can't exactly say why it's working now but it is, which is great! Julian, if you would' mind could you just tell me a bit more about this?

You have used it the way you would use a for loop in other words using the index (first parameter) into the structure you are iterating over and not making use of the actual item that is passed into the function for you.

I don't really understand what you mean. Using what I had did populate the dropdown as intended but I want to do it correctly like you have showed me but just want to understand it a bit better.
it may be cache issue, other than that I dont see any issue...
remember, js files may be cached, so press Ctrl+F5 to refresh, or clear the cache every time you change js file...
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
With respect to caching and JS files - a refresh will work but you can't really rely on this for your users / customers.

Dear customer please do a regular Ctrl + F5 in case we changed something.

A better solution is to version your scripts like so
<script src="/js/functions.js?ver=1"></script>

Open in new window

Every time you change something in functions.js increase the ver number by 1.
This allows you to benefit from caching of the file when it has not changed but force the browser to refresh the file when it has without requiring a Ctrl+F5
Thanks for the explanation Julian, it helps a lot!
You are always welcome.