jquery autocomplete from php vars - php

<?php require_once('Connections/root.php'); ?>
<?php $q = mysql_query("SELECT * FROM performer"); ?>
<script> $(document).ready(function () {
$(function() {
var availableTags = ["<?php while($r = mysql_fetch_assoc($q)) { echo $r['username']; } ?>"];
$("#search_box").autocomplete({
source: availableTags
});
});
});
</script>
the script works but it displayes : User1User2User3
and i want it to display:
User1
User2
User3
How do i add a new line after every user and where do i add the line feed
if i make it like this
var availableTags = ["<?php while($r = mysql_fetch_assoc($q)) { echo $r['username'] . " <br />"; } ?>"];
i get User1User2User3 and the br as a string

Separate your PHP logic from your Javascript code. Up top, build a PHP array first:
$tags = array();
while($r = mysql_fetch_assoc($q)) {
$tags[] = $r['username'];
}
Then in your javascript, echo the array JSON encoded:
var availableTags = <?php echo json_encode($tags); ?>;
Note: You are using deprecated mysql_* functions and should switch to mysqli_* or PDO.

As mentioned, your availableTags array has only 1 string variable.
You need to push the string to the Array.
You can try this:
var availableTags = [];
<?php while($r = mysql_fetch_assoc($q)) { ?>
availableTags.push('<?php echo $r['username']; ?>');
<?php } ?>

The generated js array is not what you expect it to be. With your code, you obtain
var availableTags = ["User1User2User3"];
whereas what you need is
var availableTags = ["User1", "User2", "User3"];
Yous should adapt your PHP code to generate the right JS.

Related

How to insert while loop data of php in jQuery array?

I want to insert while loop user data in jQuery array.
<?php
while($get_users_table_details = mysql_fetch_array($deatails)) {
if(empty($get_users_table_details["photo"])) { $pics = "photos/avatar.gif"; } else { $pics = "photos/".strip_tags($get_users_table_details["photo"]).""; }
?>
Script code between while loop
$(document).ready(function(){
$("#full").mention({
users: [{
name: '<?php echo $get_users_table_details['fullname'];?>',
username: '<?php echo $get_users_table_details['username'];?>',
image: '<?php echo $pics;?>'
}] });
});
</script>
end of script
}
end of while loop
The problem is that this shows the user details of only one user. However, I want all user details to be shown, as in this picture:
You should first build the array of users in php:
<?php
$users = []; // instatiate an empty array
while($get_users_table_details = mysql_fetch_array($deatails)) {
// build a user-array as needed later
$user = [];
$user['name'] = $get_users_table_details['fullname'];
$user['username'] = $get_users_table_details['username'];
if(empty($get_users_table_details["photo"])) {
$user['image'] = "photos/avatar.gif";
} else {
$user['image'] = "photos/".strip_tags($get_users_table_details["photo"]);
}
$users[] = $user; // add this user to the array of users
}
?>
Then pass (=echo) that to javascript via json_encode:
<script>
$(document).ready(function(){
$("#full").mention({
users: <?php echo json_encode($users); ?>
});
});
</script>
Please try this sample javascript code.
var users = <?php echo json_encode($get_users_table_details ) ?>;
$.each(users, function(key, value) {
console.log('stuff : ' + key + ", " + value);
// Do everything you want
});

Echo PHP value inside a jquery Function

I am trying to assign a php echo value to an input generated from a jquery function. But so far no luck. It breaks the function and no results are displayed along with the input field. What is the proper way for this scenario to display php value inside the query function.
PHP
$tablename = "table";
$next_increment = 0;
//$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = $db_con->prepare("SHOW TABLE STATUS LIKE '$tablename'");
$qShowStatusResult->execute();
$results = $qShowStatusResult->fetchAll(\PDO::FETCH_ASSOC);
foreach($results as $value){
$next_increment = $value['Auto_increment'];
}
var nextAutoIncrement = '"'<?php echo $next_increment; ?>'"';
Jquery
newSection.children(':nth-child(1)').children(':first').attr('id', 'auto_id_' + newNum).attr('name', 'auto_id_' + newNum).val(nextAutoIncrement).hide();
Try this
<script language="javascript" type="text/javascript">
var nextAutoIncrement = '<?php echo $next_increment;?>';
</script>
Try like this:
<script language="javascript" type="text/javascript"
var nextAutoIncrement = <?php echo $next_increment; ?>;
</script>
<script>
//if it is anumber
var nextAutoIncrement = <?php echo $next_increment; ?>;
// if ity is a string
var nextAutoIncrement = '<?php echo $next_increment;?>';
</script>
In JS code there is require to define the <script> tag:
$tablename = "table";
$next_increment = 0;
$qShowStatusResult = $db_con->prepare("SHOW TABLE STATUS LIKE '$tablename'");
$qShowStatusResult->execute();
$results = $qShowStatusResult->fetchAll(\PDO::FETCH_ASSOC);
foreach($results as $value){
$next_increment = $value['Auto_increment'];
}
<script type="text/javascript" >
var nextAutoIncrement = '<?php echo $next_increment; ?>';
</script>

How Can I Take Oracle 10G Data Into a PHP Array and Then Convert It to a JavaScript Array?

I'm trying to define a PHP array, then connect to Oracle 10g and take the data requested from the connection and put it into the PHP array.
Finally, I want to take the PHP array and convert it into a JavaScript array.
Here's what I'm trying.
Can somebody point out why this is not working and perhaps offer a solution?
Thank you.
$dbArray = array();
$conn = oci_connect("username", "password", "connecturl");
$query = 'select endpoint_name from endpoint_ref order by endpoint_name asc';
$stid = oci_parse($conn, $query);
$result = oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC))
{
foreach ($row as $item) {
array_push($dbArray, $item);
var_dump($dbArray);
echo $dbArray;
}
}
$jsArray = json_encode($dbArray);
Also, how can I set this JavaScript variable named "availableTags" to equal my newly encoded JavaScript array?
$(function() {
var availableTags = jsArray;
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
The conversion in my question was correct, the problem was the JavaScript function. This is how to properly call the JSON encoded PHP array containing the Oracle 10g data.
<script>
$(function() {
var availableTags = <?php echo json_encode($dbArray); ?>;
$( "#endPointName" ).autocomplete({
source: availableTags
});
});
</script>

Jquery autosuggest not working

Hey guys, I'm using jQuery's autosuggest plugin by using php to get the data. But it doesn't seem to work since I always get: No Results Found, even though I'm sure there are results:
Here's the php code:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$input = mysql_escape_string($_GET["q"]);
$data = array();
$mysql=mysql_connect('localhost','***','***');
mysql_select_db('jmtdy');
$query = mysql_query("SELECT * FROM users WHERE username LIKE '%".$input."%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
And the script:
<script >
$(document).ready(function () {
$("#suggestedfriend").autoSuggest("suggestedf.php");
});
</script>
<script >
$(document).ready(function () {
$("#suggestedfriend").autoSuggest(
"suggestedf.php",
{
selectedValuesProp: "value",
selectedItemProp: "name",
searchObjProps: "name"
});
});
</script>
Add the above parameters, it will start to work :)
Just look at data, that server sends you back. If you use firefox you can watch it in network tab of firebug, or if you use chrome see it in resources.
The header must be in top of the file, right after the
<?php
header('Content-type: application/json');
include_once 'resources/dbconn.php';
$term = $_REQUEST['term'];
$query = "SELECT * FROM cds WHERE titel LIKE '%$term%'";
$result = $mysqli->query($query);
$arr = array();
while ($obj = $result->fetch_array()) {
$arr[] = $obj;
}
//for jsonp echo '('.json_encode($arr).')';
echo json_encode($arr);
?>
The JS/jQuery string
<script type="text/javascript">
$(function() {
var cache = {},
lastXhr;
$("#exercise").autocomplete({
minLength: 2,
source: function(request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
lastXhr = $.getJSON("json_Search.php", request, function(data,status,xhr) {
cache[term] = data;
if (xhr === lastXhr) {
response(data);
}
});
}
});
});
</script>

Double dimensional array value from PHP

I have a PHP file that is going to write a two-dimensional array in JavaScript:
<?php
print "<script language='javascript'>";
print " extra[0][0] = new Array(1,'Bob',12);";
print " extra[0][1] = new Array(2,'Alice',18);";
..
// Need to assign the extra[1][0], extra[1][1] and so on.
print "</script>";
?>
Mu.js:
var extra = new Array();
...
How do I assign the two-dimensional array from PHP to a JavaScript variable?
json_encode is your friend: json_encode in the PHP manual
<script type="text/javascript">
var jsArray = <?= json_encode($my_array) ?>;
</script>
Yes, wvanbergen is right, json_encode is your friend. You can create the array as JSON:
<?php
$extra = array(
array(1,'Bob',12),
array(2,'Alice',18)
);
echo "var extra = " . json_encode($extra) . ";";
?>
And in your javascript it will output:
var extra = [[1,"Bob",12],[2,"Alice",18]];
<script type="text/javascript">
var jsArray = <?php json_encode($my_array); ?>;
</script>

Categories