The following code is what I am currently using to try and give the posts ID to vote.php, however this currently returns [object Object]. How would I be able to pass the correct id when a link is clicked?
<script type="text/javascript" src=".7.2/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",
data: "id=" + $(this).attr("href", "id"),
url: "vote.php"
});
</script>
<a href="javascript:;" id="1"><div id="button">Like!</div></a>
<a href="javascript:;" id="2"><div id="button">Like!</div></a>
<a href="javascript:;" id="3"><div id="button">Like!</div></a>
Thanks!
The following code is what I am currently using to try and give the posts ID to vote.php, however this currently returns [object Object]. How would I be able to pass the correct id when a link is clicked?
<script type="text/javascript" src="http://ajax.googleapis./ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",
data: "id=" + $(this).attr("href", "id"),
url: "vote.php"
});
</script>
<a href="javascript:;" id="1"><div id="button">Like!</div></a>
<a href="javascript:;" id="2"><div id="button">Like!</div></a>
<a href="javascript:;" id="3"><div id="button">Like!</div></a>
Thanks!
Share Improve this question asked Oct 22, 2012 at 11:27 PatrickPatrick 4904 gold badges8 silver badges18 bronze badges 1- Make sure to also change id="button" to class="button" :) – romac Commented Oct 22, 2012 at 11:37
3 Answers
Reset to default 3You need to bind the ajax call to a click handler:
$(document).on("click","a",function(e){
$.ajax({
type: "POST",
data: "id=" + $(this).attr("id"),
url: "vote.php"
});
});
You should consider changing it to:
<script type="text/javascript" src="http://ajax.googleapis./ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function vote(_obj) {
$.ajax({
type: "POST",
data: "id=" + $(_obj).attr("href", "id"),
url: "vote.php"
});
}
$(document).ready(function() {
$('.vote').click(function() {
vote(this);
return false;
});
});
</script>
<a id="1" class="vote"><div>Like!</div></a>
<a id="2" class="vote"><div>Like!</div></a>
<a id="3" class="vote"><div>Like!</div></a>
Some notes:
- Do not use multiple elements with the same ID on a page
- Bind events only after your DOM is loaded and ready, i.e. on or after the domready event.
In your code, you are assigning the href of the links to "id"
which does not make a lot of sense... And you should use event handlers for clicks...
<script type="text/javascript" src="http://ajax.googleapis./ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('a.likeBTN').click($.ajax({
type: "POST",
data: "id=" + $(this).attr("id"),
url: "vote.php"
}))});
</script>
<a href="javascript:;" class="likeBTN" id="1"><div id="button">Like!</div></a>
<a href="javascript:;" class="likeBTN" id="2"><div id="button">Like!</div></a>
<a href="javascript:;" class="likeBTN" id="3"><div id="button">Like!</div></a>