user1104147
user1104147

Reputation: 105

Function not defined - jQuery/Javascript

Another hapless noob... Okay, so I've looked everywhere to try and find out how to make this jQuery/JavaScript function, I hope it's just a mistake in my syntax, but here's my code:

<script type="text/javascript">

$(function()
{
        function loadNext(choice) {
            $("#thequestion").load("question.php", { ans: choice, id: "<?php echo $row['id']; ?>", nextId: "<?php echo $nextQuestionId; ?>" } );

            $("#graph").load("graph.php", { id:"<?php echo $row['id']; ?>", nextId: "<?php echo $nextQuestionId; ?>" } );
            alert("loadNext activated");
        }

});
</script>

I then call the loadNext(choice) function using an onclick event like so: onclick="loadNext(YorN);".

Following this I get a 'loadNext is not defined' error.

Amongst the answers that I would accept are: "Y U NO LEARN!" and "You are silly."

Here is a similar problem.

Thanks.

Upvotes: 0

Views: 3966

Answers (5)

xdazz
xdazz

Reputation: 160833

Because loadNext is not in global scope. You can define it in global scope, or even better solution is to use .click() to bind your click event.

Upvotes: 1

Naren
Naren

Reputation: 1920

The outer "$(function().." you have on your first line limits your scope - the loadNext function is only available within this block and will be undefined outside of it.

The easy way to get around this is to just define the "loadnext" function outside the $(function()..) block but this is wrong for two reasons:

  1. This makes the function global across your entire application, and polluting the global namespace is a no-no.
  2. Inline javascript like "onclick" is bad in general - this blurs the line between presentation and logic and makes debugging a pain.

To get around this, use the jquery bind events to attach your event handlers; i.e.,

$("#myfancybutton", click(function(){ loadNext(choice) }); within your $(function()..) bloc

Upvotes: 2

vrunoa
vrunoa

Reputation: 776

why dont you just put your loadNext function outside of the $(function(){}) ?

Upvotes: 1

Carlos Barbosa
Carlos Barbosa

Reputation: 1432

because you have a function inside a function

 (function()
{
        function loadNext(choice) {
            this is bad
        }

function loadNext(choice) {
            this is good
        }

onclick="loadNext()"

no probs

Upvotes: 1

Kenaniah
Kenaniah

Reputation: 5201

The loadNext function you just defined is local to the scope of your anonymous function. If you want to access it globally, then define it globally (outside of your onready handler).

Upvotes: 4

Related Questions