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];
}
Related
I have an associative array. After I select my records from my table (with two columns: objName,objCost), I want to save them in my array like this:
array(
'objName'=>$row['objName'],
'objCost'=>$row['objCost']
)
How should I do this?
This is my code:
$output = '';
$arr = array();
$sql = "SELECT * FROM obj WHERE objName LIKE '%" . $_POST["search"] . "%'";
$result = $db->query($sql) or die(mysql_error());
if ($result->rowCount() != 0) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
//here i should insert my rows into my array
}
$json_arr = json_encode($arr,JSON_UNESCAPED_UNICODE);
echo $json_arr;
} else {
echo 'Data Not Found';
}
According to your code,
$arr[] = ['objName'=>$row['objName'],'objCost'=>$row['objCost']];
Then you can encode the array and pick up the object on the other side with javascript or php. Which ever suits you
json_encode($arr);
In you Ajax success, get the objects and use the values as you deem fit
success: function (data) {data = JSON.parse(data);
for(var i = 0; i < data.length; i++){
alert(data[i].objName);
}
}
see jQuery loop over JSON result from AJAX Success? on how to loop through your results in jquery
Hi I have some table say fro example table1 ,table2 in my mysql databse.
I need to get following json result from php.
Can anyone suggest how to achieve this?
any good tutorial doing same is also helpful.
I am able to convert database result in simple json response but custom response is something difficult for me.
{
response:ok
tables:[
{
name:table name
data:[
{
fieldname1:value1
fieldname2:values2
},
{
fieldname1:value1
fieldname2:value2
}
.
.
]
},
{
name:table name1
data:[
{
fieldname1:value1
fieldname2:values2
},
{
fieldname1:value1
fieldname2:value2
}
.
.
]
},
]
}
}
Quoting from How to convert mysql data base table data in json using php, once you have your table names you can do for each of them.
$result = array();
$result['response'] = 'ok'
foreach ($tables as $tableName) {
$query = mysql_query("SELECT * FROM $tableName");
$rows = array();
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
$result['tables'][] = array(
'name' = $tableName,
'data' = $rows
)
}
print json_encode($result);
So I have a object that is successfully pulling all the rows from a database and storing them like so:
Object {models: Array[2]}
[Object, Object]
0: Object
address: "1234 Cooper"
firstname: "Rick"
lastname: "Bross"
address: "1234 Cooper"
__proto__: Object
How can I restructure this so I can just say:
alert(potentialModels.rickbross.firstname)
//rickbross = *whatever model i want to find*
and it output:
"Rick"
Here is how I am currently creating this object:
<?php
if($_SESSION['username']) {
$result = mysql_query("SELECT * FROM `potentials`") or die(mysql_error());
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
// $rows[] = $r; has the same effect, without the superfluous data attribute
$rows[] = $r;
}
// now all the rows have been fetched, it can be encoded
$myJSON = json_encode(array('models' => $rows));
?>
and how I am getting it in the console:
var potentialModels = <?php print($myJSON); ?>;
console.log(potentialModels);
Change:
$rows[] = $r;
To:
$rows[strtolower($r['firstname'].$r['lastname'])] = $r;
And you can use:
alert( potentialModels.models.rickbross.firstname);
If you want to drop the models, stop adding it to your JSON here:
json_encode(array('models' => $rows));
By changing it to:
json_encode( $rows);
I use jQuery to run a function in PHP to get data from the database.
$.ajax({
url: 'service.php',
data: { functie: type, param: radiobutton },
dataType: 'json',
success: function (data) {}
});
Everything works. Except the strings with special characters return as null in the succes function. For example: ñ
The answer for this is here explained:
Special characters break json returned to jQuery
But it doesn't work for me.
In php I tried:
$result = mysql_query("SELECT * FROM wines");
$array = array();
while($row = mysql_fetch_assoc($result)){
$array[]=htmlentities($row);
}
Who knows how to make sure everything returns in a good way?
In your while statement you're using htmlentities on an array, not a string (each key in the array is a column in the database).
You could do either of the following:
Use array_map:
while($row = mysql_fetch_assoc($result)){
$array[] = array_map("htmlentities", $row);
}
or change your while loop:
while($row = mysql_fetch_assoc($result)){
foreach ($row as $key => $value) {
$row[$key] = htmlentities($value);
}
$array[] = $row;
}
I'm working on passing 2 fields of SQL through php to javascript. I have read many tutorials on how to create a multidimensional javascript array. Where I get confused is how to code from php to javascript. I have seen a couple of tutorials on how to get the php data to javascript, but none on how to do this with 2 dimensions.
My first hangup is that if I'm creating a multidimensional array I need to count the number of records in my sql data before I declare the java array right?
update:
I got the data to JSON format as suggested below. Is there a way for me to get all of the contents printed to the web page so that I can see them and then narrow down what is displayed?
update III:
code:
mysql_connect("localhost", "bikemap", "pedalhard") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$data = mysql_query("SELECT * FROM gpsdata");
$new_row = array();
$new_column = array();
while($info = mysql_fetch_array($data)){
foreach( $info as $row_num => $row)
{
$thisItem = $row;
$new_row[] = $thisItem;
}
array_push($new_column = $new_row);
}
$json = json_encode($new_column);
echo $json;
?>
Working code:
$data = mysql_query("SELECT * FROM gpsdata");
$aData = array();
while($row = mysql_fetch_assoc($data))
$aData[$row['idgpsdata']] = array($row['userID'],$row['date'],$row['lat'], $row['longi'], $row['alt']);
$json = json_encode($aData);
echo $json;
Fill a PHP array first, it's easier than building the string for a javascript array. Then - as ThiefMaster said as comment - use JSON to make the javascript array.
In PHP, you can use JSON PECL extension
<?php
$arr = array( 1=>array(3,4),
2=>array(4,5));
$json = json_encode($arr);
echo $json;
?>
Output
{"1":[3,4],"2":[4,5]}
In Javascript
var obj = JSON.parse('{"1":[3,4],"2":[4,5]}');
for(var i in obj){
for(var j in obj[i]) {
console.log(obj[i][j]);
}
}
JSON.Parse is for Gecko (Firefox alike), for cross-browser javascript JSON parse check jQuery.parseJSON or https://stackoverflow.com/search?q=json+parse+javascript
Sample implementation in PHP/jQuery, would be something like this:
json.php
$arr = array( 1=>array('Name', 'Age'),
2=>array('Fares','18'));
$json = json_encode($arr);
echo $json;
json.html
<html><head></head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script>
$.getJSON('json.php', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
</script>
</body>
</html>