Reputation: 169
I'm new to jquery and was wondering if someone can help me with, what i believe is an easy solution.
I am trying to get the id of a link when click and then alert the id out like this:
What am I missing here? cause firebug is giving me a 'id is not defined' error.
$(document).ready(function(){
$("a.category").click(function(){
$.post("index.php", { id: "$(this).attr('id')"},
function(data){
alert("Data Loaded: " + id);
});
//return false to insure the page doesn't refresh
return false;
});
});
Thanks for any help on this.
Upvotes: 0
Views: 159
Reputation: 887195
By writing { id: "$(this).attr('id')" }
, you are creating an object with the id
property set to the literal string "$(this).attr('id')"
.
To post the actual ID of the clicked element, you need to remove the quotes and set the id
property to the value of the expression, like this: { id: $(this).attr('id') }
.
Also, the expression { id: $(this).attr('id') }
creates an object with an id
property.
It does not create any id
variable, so you can't use the id
non-variable in the callback.
To fix this, you need to make a variable, like this:
$(document).ready(function() {
$("a.category").click(function(){
var id = $(this).attr('id');
$.post("index.php", { id: id },
function(data){
alert("Data Loaded: " + id);
}
);
//return false to insure the page doesn't refresh
return false;
});
});
Upvotes: 2