Is there a way to hide autocomplete arrays from HTML source? - javascript

I have a JQuery autocomplete function going, fed by a json_encoded PHP array. Everything is functioning, but when I right click on the site to view the page source, I can see the entire array. What is this array contained sensitive information? Is there a better way to organize this code, making it more private with the same level of functionality?
On the main PHP/HTML page:
<?php include 'autocomplete.php'; ?>
which includes:
<?php
// connect to db
//fetch first and last name
$sql="SELECT first, last FROM names";
$result = mysqli_query($web_dbi, $sql) or die("Error " . mysqli_error($web_dbi));
while ($f=mysqli_fetch_array($result)) {
$names[] = array(
'label' => $f['first'] . " " . $f['last'];
);
}
echo json_encode($names);
?>
back on the main PHP/HTML page I have some JQuery:
... (JQuery CDNs)
<script type="text/javascript">
$(function() {
$( "#inputfield" ).autocomplete({
source: "autocomplete.php",
minLength: 1,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
The main issue is that in the source of the HTML page, this is visible:
$(function() {
var autocompletevalues = ["name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name"];
$( "#inputfield" ).autocomplete({
dataType: "json",
source: availableTags
});
});

It has to be like this:
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
Ref: JQuery Autocomplete
search.php has to ftech json values which can then be displayed as a part of autocomplete.
Refer to this Fiddle: http://jsfiddle.net/handtrix/32Bck/
Update 1:
while($product_search->fetch())
{
$data[] = array(
'label' => trim($product_code)
);
}
echo json_encode($data);
JS Code:
$("#inputfield").autocomplete({
source:'search.php',
minLength:4
});

Related

JQuery autocomplete - Display multiple values

I want to display multiple values to the autocomplete box.
In my understanding JQuery autocomplete uses the key "value" as default to display text to the box.
But I want to display the keys "value", "company" and "tags" which I get by the search result.
Here is what I have:
My Database query - Here only 'value'=>$product->title gets used.
public function autoComplete(Request $request) {
$query = $request->get('term','');
$products = Products::where('title', 'LIKE', '%' . $query . '%')
->orWhere('company', 'LIKE', '%'. $query .'%')
->orWhere('tags', 'LIKE', '%'. $query .'%')
->get();
$data=array();
foreach ($products as $product) {
$data[]=array('id'=>$product->id,
'value'=>$product->title,
'company'=>$product->company,
'tags'=>$product->tags);
}
if(count($data))
return $data;
else
return ['value'=>'No Result Found','id'=>''];
}
My JQuery autocomplete Script
<script>
$(function()
{
$( "#search_text" ).autocomplete({
source: "{{ route('searchajax') }}",
minLength: 1,
select: function(event, ui) {
$('#search_text').val(ui.item.value);
},
open : function(){
$(".ui-autocomplete:visible").css({top:"+=13"});
},
});
});
My Input Field
<div class="col">
<input class="form-control form-control-lg form-control-borderless ui-autocomplete-input"
id="search_text"
type="search"
name="q"
value="{{ isset($s) ? $s : '' }}"
placeholder="Search for Titles, Companys or Tags"
autocomplete="off" />
If it helps, I use Laravel for this project.
would it not be easiest to manipulate the 'value' field server side to get the desired result? for example like this
'value'=>$product->title.', '.$product->company.', '.$product->tags);
I found the solution myself with help of the
JQueryUI Documentation
I had to manipulate the renderItem() extension point.
This is my script now, work perfectly fine:
<script>
$(function()
{
$( "#search_text" ).autocomplete({
source: "{{ route('searchajax') }}",
minLength: 1,
select: function(event, ui) {
$('#search_text').val(ui.item.value);
return false;
},
open : function(){
$(".ui-autocomplete:visible").css({top:"+=13"});
},
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div><strong>" + item.value + "</strong><br>" + item.company + "</div>" )
.appendTo( ul );
};
});

jquery autocomplete input field nothing happens

I want to implement one autocomplete input field but when I start to insert some text nothing happens, for one sec the "busy circle" shows up and that is all.
Here is my code:
html>
<div class="products-inv"><?php echo $product_name ?></div>
<input type="text" id="product_name" name="product_name" />
the first div is test for displaying the php variable value what shows up well
jquery>
jQuery( function() {
function log( message ) {
jQuery( "<div>" ).text( message ).prependTo( "#log" );
jQuery( "#log" ).scrollTop( 0 );
}
jQuery( "#product_name" ).autocomplete({
source: "../route/to/search.php",
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
} );
and the search.php file content>
$query = 'database data';
$db->setQuery( $query );
$product_name = $db->loadResult();
the error console is empty.
thanks in advice
your server side code does not return the data expected by the plugin.
From the documentations of the jQuery autocomplete plugin about the source option
When a string is used, the Autocomplete plugin expects that string to
point to a URL resource that will return JSON data
your search.php script must return the items you want to suggest to the user (show up in the autocomplete list )
that is an example:
/*term is a parameter generated by the plugin and contains
the string the user has typed in the input*/
$_GET['term'] = isset($_GET['term']) ? $_GET['term'] : null;
//manage your own query depending on your database and preferred way for db interactions
//$query = "select product_name from product where product_name like ?";
//$term = "%{$_GET['term']}%";
//$stmt = $mysqli->prepare($query);
//$stmt->bind_param("s", $term);
//$stmt->execute();
//$result = $stmt->get_result();
$autocompleteList = [];
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$autocompleteList[] = $row['product_name'];
}
die(json_encode($autocompleteList));

PHP array as JSON response for jQuery autocomplete

I have a search form where I want to display suggestions via jQuery autocomplete when 3 characters are typed. The suggestions are drawn from a mySQL DB.
What happens: jQuery does successfully transmit the typed chars to the PHP file, where they successfully get embedded in an mySQL query.
When I open the PHP file separately with an assumed search term, f.e. like this: /soplogsearch.php?term=xyz it works perfectly and I see the aimed at result of echo json_encode($return_arr);
but back on the HTML search form file autocomplete doesn't suggest a thing. I have no errors in the console. I tried to echo the json_encode elsewhere on the HTML file and its output was Null.
I have made a fiddle for the (very simple) Javascript/jQuery and HTML set up: https://jsfiddle.net/9bf6s07f/1/
the relevant PHP code looks like this:
if (isset($_GET['term']))
{
$term = $_GET['term'];
$termwild = "%$term%";
$return_arr = array();
$service = mysql_query("SELECT DISTINCT service FROM master WHERE service LIKE \"" . $termwild . "\"");
while ($data = mysql_fetch_array($service))
{
$return_arr[] = $data[0];
}
json_encode($return_arr);
echo json_encode($return_arr);
}
EDIT: For quicker access I'm including the HTML and jQuery parts of the code here instead of link you to the fiddle https://jsfiddle.net/9bf6s07f
<body>
<label>Service:</label>
<input type='text' name='' value='' class='auto'>
</body>
and jQuery:
$(document).ready(function() {
$(function() {
$(".auto").autocomplete({
source: "soplogsave.php",
minLength: 3
});
});
});
Does someone know what I'm doing wrong? I tested autocomplete separately with a set of javascript variables and it worked fine.
EDIT 2: Because all of the comments seem to imply my PHP is wrong and I'd have an error in the console, I made a screenshot from the network tab of the console: http://i.imgur.com/i6nAQ98.png
This is how I have achieved it in my code:
PHP
$param = $_GET["term"];
$stk_adddep = "
SELECT * FROM stocktake_products WHERE stocktake_id = '{$stocktake_id}' AND is_deli = 0 AND (product_code LIKE '%{$param}%' OR product_name LIKE '%{$param}%'); ";
//FB::info($stk_adddep);
//echo $stk_adddep;
//die();
$result = db::c()->query($stk_adddep);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['itemCode'] = $row['product_code'];
$row_array['itemDesc'] = $row['product_name'];
//$row_array['itemPrice'] = $row['unit_cost_price'];
array_push( $return_arr, $row_array );
}
/* Free connection resources. */
//mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
And then javascript
$(document).ready(function(){
// Use the .autocomplete() method to compile the list based on input from user
var url10 = '<?php echo Navigation::gUrl('/users/admin/stocktake_details_cocktails.php', array('stocktake_id' => $stocktake_id, 'action' => 'find_products'));?>';
$('#itemCode').autocomplete({
source: url10,
minLength: 1,
select: function(event, ui) {
var $itemrow = $(this).closest('tr');
// Populate the input fields from the returned values
$itemrow.find('#itemCode').val(ui.item.itemCode);
$itemrow.find('#itemDesc').val(ui.item.itemDesc);
//$itemrow.find('#itemPrice').val(ui.item.itemPrice);
// Give focus to the next input field to recieve input from user
$('#itemQty').focus();
return false;
}
// Format the list menu output of the autocomplete
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.itemCode + " - " + item.itemDesc + "</a>" )
.appendTo( ul );
};
See if you can maybe apply this to your code?
The answer was posted in the comments by user #n00dl3.

Jquery autocomplete source php function

I would like to attach a php function as a source for my autocomplete functionality, The problem is I am not getting any results back.
PHP function
function getUser(){
$users = R::findAll('users');
foreach ($users as $user) {
echo '<option value="'. $user->name .'" ';
if($_POST['filterUser'] == $user->name){
echo "selected";
}
echo $user->name . '</option>';
}
}
Auto completion
$( "#enterUser" ).autocomplete({
source:'test.php?str=' + $('filterUser').val(),
messages:
{
noResults: '',
results: function() {}
},
select: function( event, ui )
{
var selectedObj = ui.item;
},
autoFocus: true
});
});
In the autocomplete declaration, your source property must be the name of your php file (with some parameters).
Example:
source: 'your_php_file.php?str=' + $('filterUser').val()
In the PHP you must call the function you want to reach, and be sure that it echoes the appropriate JSON string.

jQuery autocomplete field not autocompleting when getting data from remote database

I'm trying to get a jQuery autocomplete field to work with data from a remote DB, and I'm having no luck. Here's what I've attempted so far:
1.I have all of the necessary links to the source code in my header.
2.I have the following jQuery script written:
<script>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#projNo0" ).autocomplete({ //projNo0 is the name of the autocomplete field
source: "projects.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
3.This is the PHP backend that's supposed to populate the autocomplete field projNo0 (the DB connection is handled elsewhere in the same file):
$return_arr = array();
if ($con2) //If the DB connection is successful
{
//Get the user's input from projNo0
$ac_term = "%".$_GET['term']."%";
$query = $con2->prepare("SELECT CodeID FROM CodeTable WHERE
CodeID LIKE :term");
$data = array('term'=>$ac_term);
$query->execute($data);
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$row_array['CodeID'] = $row['CodeID'];
array_push($return_arr,$row_array);
//echo $row['CodeID']; //line used for testing
//echo '<br />'; //line used for testing
}
}
4.And here is the HTML for my autocomplete field. It's part of an array:
<p class="ui-widget">
<input type="text" name="projNo[]" id="projNo0" value="<? php echo $projNo[0]; ?>" />
</p>
I can confirm that there's no problem connecting to the remote DB. I'm able to echo out the array of values the SELECT statement returns. The jQuery script only works, however, when I hardcode an array of values into it. (Replace source "projects.php" with ["Bob","Carol","Ted","Alice"], for example.) When I right-click on the field and inspect it, the network activity shows that projects.php is being called and that it's accepting my input, appending it as a GET variable. The status of that activity is "OK". But I get no drop-down list of autofill suggestions.
Where is the break between my application and the database? I'm assuming that's where the problem is, since the script works with hardcoded values.
Replace this
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$row_array['CodeID'] = $row['CodeID'];
array_push($return_arr,$row_array);
//echo $row['CodeID']; //line used for testing
//echo '<br />'; //line used for testing
}
With this
echo json_encode(array_values($query->fetchAll(PDO::FETCH_COLUMN, 0)));
The point is - autocomplete expexts JSON-encoded string as an answer, and you return nothing from your script. Using array_reduce to get the resulting array is just my preference.

Categories