0

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

4

2 回答 2

4

在 jQuery 中,您将使用 Ajax 获取对 CodeIgniter 控制器的请求。假设您的控制器称为用户,您的函数称为 update_favorites。jQuery 调用可能如下所示:

$.get('http://mysite.com/users/update_favorites/user_id/message_id');

然后,您的控制器将找到 user_id 和 message_id 的 URL 参数,并使用这些参数加载您的模型。该模型将对数据库进行更改。

祝你好运!

于 2011-01-18T17:26:15.453 回答
1

除了 Summer 的 $.get 方法之外,您还可以以几乎相同的方式使用 jQuery 的 $.post() 方法。我更喜欢使用 post,因为 Codeigniter 被编写为支持 post 请求而不是 get 请求。

于 2011-01-18T18:57:26.717 回答