i've been working on a project for a while now using CodeIgniter and i've been fighting with an issue for several days. I'm displaying a series of images from the database with a foreach loop on the index view and each image you can like or dislike, and this works fine, the problem is that the page only displays the amount of likes for one image. So i figured that the solution would be to send the data to the public function index()
method on my controller and then make a query in the model and return all to the view. You think there is another way to pull this off?
This is my ajax request
jQuery(document).ready(function($) {
var id = $("*#id_image").val();
$.ajax({
url: 'index.php/inicio/display_votes_index',
type: "POST",
dataType: "JSON",
data: {id_image: id},
success: function (response) {
$("#displayVote"+id).html(response.msg + " puntos");
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
This is my view
<aside class="container">
<div class="row col-md-8">
<?php
foreach ($images as $value) {
?><h1 style="font-size:20px;"><a href="#"><?= $value->title; ?></a></h1><?php
?><img src="<?= base_url(); ?>images/<?= $value->path; ?>" alt="<?= $value->title ?>" class="img-responsive" width="500"/>
<a href="#" style="color: #636363; margin-top:10px;display:block" id="displayVote<?= $value->id_image; ?>"></a><br/>
<button type="button" style="margin-right:5px;" class="btn btn-default btn-md" onclick="voteUp(<?= $value->id_image; ?>)"><i class="fa fa-arrow-up"></i></button>
<button type="button" style="margin-right:5px;" class="btn btn-default btn-md"><i class="fa fa-arrow-down"></i></button>
<button type="button" style="margin-right:5px;" class="btn btn-default btn-md"><span class="glyphicon glyphicon-comment"></span></button>
<input type="hidden" id="id_image" value="<?= $value->id_image; ?>"/>
<hr/>
<?php
}
?>
</div>
</aside>
This is the model
public function get_all_votes($id_image)
{
$sql = "SELECT COUNT(vote) AS vote_up FROM likes WHERE id_image = ? AND id_status = 1";
$query = $this->db->query($sql, $id_image);
$row = $query->row();
return $row->vote_up;
}
And this is the controller recieving the data
public function display_votes_index()
{
$id_image = $this->input->post('id_image');
$votes = $this->vote_model->get_all_votes($id_image);
if ($votes) {
echo json_encode(['success' => TRUE, 'msg' => $votes]);
} else {
echo json_encode(['success' => FALSE, 'msg' => 'Error']);
}
}
PD: if i use eq()
like this: var id = $("#id_image").eq(1).val();
the page shows the amount of likes of the second image in the loop, and if i change the numbers displays the likes for the other images. Is there a way to select all the id's of all the images? i tried with eq(*)
but it didn't work. Thanks!!!