The ajax request functions where:
success: function(data) {
$('#totalvotes1').text(data);
}
and where <span id="totalvotes1">,
but I need it to work with unique id’s where:
success: function(data) {
$('#total_' + $(this).attr("id")). text(data);
}
and where <span id="total_vote_up_<?php echo $mes_id; ?>">
and <a id="vote_up_<?php echo $mes_id1; ?>">
I cannot figure out what is wrong with the following code. If anybody has an easy fix with json I would try that but I have no idea how json works. I would love it if somebody could just help me debug this code here
general.js:
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var eData = $(this).attr("data-options");
var dataString = 'id='+ id + '&' + eData ;
var parent = $(this);
if(name=='up')
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "up.php",
data: dataString,
cache: false,
success: function(data) {
$('#total_' + $(this).attr("id")).text(data);
}
});
}
});
});
});
index.php
<div id="main">
<div id="left">
vote_up_<?php echo $mes_id1; ?>
<span class='up'><a id="vote_up_<?php echo $mes_id1; ?>" class="vote" name="up" data-options="key1=<?php echo $mes_id1;?>&key2=<?php echo $mes_id2;?>&key3=<?php echo $totalvotes1;?>&key4=<?php echo $totalvotes2;?>"> <img src="up.png" alt="Down" /></a></span><br />
<span id="total_vote_up_<?php echo $mes_id1; ?>"><?php echo $totalvotes1; ?></span><br />
</div>
<div id="message">
<?php echo $message1; ?>
</div>
<div class="clearfix"></div>
</div>
Identation and enters are your friends.
Try doing something like this:
Most jQuery functions change the context, so “this” inside the success function does not point to the “.vote” element. You have to save the reference to the element (usually with something like “var that = this”) and use this reference inside the success function.
Edit:
As Matt Burland pointed out, you already have both the clicked element reference saved (parent) and the id saved, so this can be solved with something like: