So, I am using the mention.js library to add a @mentionUser functionality into my application. I am wondering what is the best way to replace the array with an array I build, fetching users from my database.
I have build the query to fetch the users, I'm just not sure how to use the resulting array in jQuery below.
PHP code (pseudocode mostly, will ofc use PDO)
$fetchUsers = mysql_query("SELECT * FROM users1 WHERE organisationId = '1'");
$results = array();
while ($row = mysql_fetch_assoc($fetchUsers)) {
$results[] = $row['name'];
}
Thanks alot!
<textarea id="full"></textarea>
<script>
$("#full").mention({
delimiter: '@',
users:
[{
username: "ashley"
}, {
username: "roger"
}, {
username: "frecklefart123"
}]
});
</script>
Have your PHP script return a JSON encoded array of user objects...
$fetchUsers = mysql_query("SELECT * FROM users1 WHERE organisationId = '1'");
$results = array();
while ($row = mysql_fetch_assoc($fetchUsers)) {
$results[] = array(
'username' => $row['name']
);
}
echo json_encode($results);
And then use jQuery's $.getJSON
...
$.getJSON('/users.php', function(data) {
$("#full").mention({
delimiter: '@',
users: data
});
});
Simples :)
To answer your second question; use some regex (note my example is very basic)...
$string = '@matt @james @seb';
if (preg_match_all('/@(\w+)/i', $string, $matches)) {
$mentions = $matches[1];
}