On my user inbox from my user messaging system I am building a feature where a user can make an email message a favourite message.
I have created 2 methods in my messages model. One updates the 0 in the 'messages' table, 'favourite' column to 1 which would mean the user wants the message to be a favourite. Also the image the user clicks on to make the message a favourite turns from grey to colour.
Then I do this same process again if a user wants to make the message not a favourite. The 1 is updated to a 0 and the image turns greyed out again.
Below is my jquery/javascript that basically does something if the box is checked (image is in colour) and something else if the box is not unchecked (image greyed out).
// favourite check box
$('input.favourite:checkbox').simpleImageCheck({
image: '<?php echo base_url()?>images/messages/check.png',
imageChecked: '<?php echo base_url()?>images/messages/unchecked.png',
afterCheck: function(isChecked) {
if (isChecked) {
//query to db from php to update favourite number to 1
}
else (!isChecked)
{
//query to db from php to update favourite number to 0
}
}
});
What I am trying to figure out is the best way to called my 2 db queries in my model:
public function favourite_checked($message_id)
{
$username = $this->session->userdata('username');
return $this->db->query("UPDATE messages SET favourite = 1 WHERE id = $message_id AND to_user = '$username'");
}
public function favourite_unchecked($message_id)
{
$username = $this->session->userdata('username');
return $this->db->query("UPDATE messages SET favourite = 0 WHERE id = $message_id AND to_user = '$username'");
}
What would be the best way to do this? Calling a model directly in a view is bad practice isn't it?
So how could I achieve what I would like to achieve?
Could a controller act as a middle man?
If so how would I even call a controller in a javascript function?
I always appreciate the advice given on here. Thanks in advance
In the jQuery, you would use an Ajax get request to a CodeIgniter controller. Say your controller is called users, and your function is called update_favorites. The jQuery call might look like this:
$.get('http://mysite.com/users/update_favorites/user_id/message_id');
Your controller would then find the URL arguments for user_id and message_id, and load your model with those arguments. The model would make changes to the database.
Good luck!