Reputation: 117
I have a simple javascript code that calls another page using AJAX to update my database records. Im using onclick
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)
{
$.ajax({
'url': 'addFeatured.php',
'type': 'GET',
'dataType': 'json',
'data': {itemid: itemId},
'success': function(data)
{
if(data.status)
{
if(data.added)
{
$("span#success"+itemId).attr("innerHTML","Added Dog to Featured Categories.");
}
else
{
$("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");
}
});
}
</script>
I really have an interest in learning javascript and understanding how it works. Any pointers would be Great!
Upvotes: 0
Views: 171
Reputation: 6381
you have missing letter in your code
replace
<script type="text/javasript">
with
<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
Upvotes: 3