CodeIgniter AJAX messages submission security issue
First of all you should use site_url() in your jquery code instead of base_url() as it provides url flexibility. For more info visit http://codeigniter.com/user_guide/helpers/url_helper.html

And in your controller code i suggest you to use bulk insert instead of loop insert. So you may use this piece of code:

foreach( $pieces as $user_id2)
{
    $insert_arr[] = array('user_id1'=&gt; $user_id, 'user_id2'=&gt; $user_id2, 'message'=&gt;$msg);
}

$this-&gt;db-&gt;insert_batch('messages', $insert_arr);