Reputation: 105
I have a script which allows user to like(+1) a record. Everything is working, but I don't know how to show a new value from DB after button is pressed (without refresh). I'm using codeigniter and I'm not really know a lot about jquery.
My script:
<script type="text/javascript">
var base_url = '<?php echo base_url();?>';
jQuery(document).ready(function(){
$('.like').click(function() {
var id = $(this).attr("uid");
$.ajax({
url: base_url+'quotes/quotes_rating',
type: 'GET',
data: {'id': id}
});
});
});
</script>
My controller:
public function quotes_rating() {
$id = $this->input->get('id');
$this->quotes_model->write_likes($id);
}
Model function write_likes() saves records into DB. This is my model function which shows how many likes has a record:
public function all_likes($id)
{
$sql = "select COALESCE(sum(like),0) as likes from rating WHERE record_id = '{$id}'";
$likes = $this->db->query($sql)->row_array();
return $allikes['likes'];
}
What I have to change in this code?
When user will click .like button, he shoud see a new value from database. Thank you!!!
Upvotes: 0
Views: 2828
Reputation: 355
<script type="text/javascript">
var base_url = '<?php echo base_url();?>';
jQuery(document).ready(function(){
$('.like').click(function() {
var id = $(this).attr("uid");
$.ajax({
url: base_url+'quotes/quotes_rating',
type: 'GET',
data: {'id': id}
success: function(data) {
$("someelementyouwanttoseelikesin").html(data);
//data will contain anything you echo in your php script!
}
});
});
});
</script>
Upvotes: 0
Reputation: 13756
jQuery(document).ready(function(){
$('.like').click(function() {
var $this = $(this);
$.ajax({
url: base_url+'quotes/quotes_rating',
type: 'GET',
data: {'id': id},
dataType: 'html',
success: function(d){
$this.html(d); //will set html of clicked link
}, error: function(){ //code for error }
});
});
Upvotes: 1