Matthew Davis Matthew Davis - 1 year ago 88
Ajax Question

Javascript function not properly defined?

I have a simple javascript code that calls another page using AJAX to update my database records. Im using

in a link to pass my variable and call the function. In debug, I get the common error "Function addFeatured not defined".

I have read many posts here on StackOverflow and I realize the most common problem I've found is that the function itself, while defined, is not accessible globally. I'm very new to javascript, and still don't fully understand how to tell if my particular script is global or not. I have looked at other scripts from slideshows and my one script from a lightbox effect, and what I have seems (to me) to be what it should, however, my lightbox is not using an onclick handler.

It is also my understanding, from what I've read so far, that using onclick in markup is not a good practice. Is this generally true? If so, what would be the proper way to accomplish what Im trying to do?

Here is the code block from my page (exactly as I have written in my IDE):

<li><a onclick="addFeatured(<?php echo $r['id']; ?>)"><i class="icon-trash"> </i> Add to Featured</a></li>
<script type="text/javasript">

function addFeatured(itemId)
'url': 'addFeatured.php',
'type': 'GET',
'dataType': 'json',
'data': {itemid: itemId},
'success': function(data)
$("span#success"+itemId).attr("innerHTML","Added Dog to Featured Categories.");
$("span#success"+itemId).attr("innerHTML","This item is already on your list");
'beforeSend': function()
$("span#success"+itemId).attr("innerHTML","Adding Dog to Featured...");
'error': function(data)
// this is what happens if the request fails.
$("span#success"+itemId).attr("innerHTML","An error occureed");

I really have an interest in learning javascript and understanding how it works. Any pointers would be Great!

Answer Source

you have missing letter in your code


<script type="text/javasript">


<script type="text/javascript">

using type other than text/javascript prevents browser from parsing the contents

bonus tip - don't use attr('innerHTML', ...) because it is wrong on many levels... element.innerHTML / $(element).html() (if you use jQuery) should be used instead

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download