jquery autocomplete input field nothing happens - javascript

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));

Related

How to add a link for a popup window when user selects a particular variation

I'm using PopupMaker plugin for wordpress to create the popup up. This works by using a click trigger on a css selector of your choosing.
With this line of code I can output the variations for the particular product when I'm on its single product page.
add_action( 'woocommerce_before_add_to_cart_quantity', 'dump_attributes' );
function dump_attributes() {
global $product;
var_dump($product->get_attribute('size'));
}
I need to output a click-able link only when the customer selects a certain variation from the drop down.
The problem I have is generating that link only when a user selects the variation 'Drum'.
I was able to give this a little more thought. First, we need to give the variation data that Woo sends via JSON a little extra value. I'm checking for a "black" color attribute:
if( 'black' === strtolower($variation->get_attribute('color')) ){
But you will want to change to suit your size attribute.
Next, I define the link as
$kia_data['custom_link'] = sprintf( '%s', __( 'Your Link', 'your-textdomain' ) );
This is just a link to google and so you'll need to change that.
Next, we add an empty <div> placeholder. And finally we load some scripts on variable products and listen for the found_variation event. When we get it, we get the variation from the JSON data and we can check for the custom_link we defined earlier and dump it into the empty holder <div>.
That's probably clear as mud, but here's the full code snippet:
/**
* Add data to json encoded variation form.
*
* #param array $data - this is the variation's json data
* #param object $product
* #param object $variation
* #return array
*/
function kia_available_variation( $data, $product, $variation ){
if( 'black' === strtolower($variation->get_attribute('color')) ){
$kia_data['custom_link'] = sprintf( '%s', __( 'Your Link', 'your-textdomain' ) );
} else {
$kia_data['custom_link'] = false;
}
return array_merge( $data, $kia_data );
}
add_filter( 'woocommerce_available_variation', 'kia_available_variation', 10, 3 );
/**
* holder for display link
*/
function kia_custom_varition_link() {
echo '<div class="woocommerce-variation-link"></div>';
}
add_action( 'woocommerce_single_variation', 'kia_custom_varition_link', 5 );
/**
* Add scripts to variable products.
*/
function kia_on_found_template_for_variable_add_to_cart() {
add_action( 'wp_print_footer_scripts', 'kia_variable_footer_scripts' );
}
add_action( 'woocommerce_variable_add_to_cart', 'kia_on_found_template_for_variable_add_to_cart', 30 );
function kia_variable_footer_scripts() {
?>
<script type="text/javascript">
jQuery( document ).ready(function($) {
$('form.cart')
.on('found_variation', function( event, variation ) {
if ( variation.custom_link ) {
$link_html = variation.custom_link;
$(this).find( '.woocommerce-variation-link' ).html( $link_html ).show();
} else {
$(this).find( '.woocommerce-variation-link' ).html('').hide();
}
}).on('reset_variation', function( event, variation ) {
$(this).find( '.woocommerce-variation-link' ).html('').hide();
});
});
</script>
<?php
}
Here is the result:
Figured out one way to solve it using jQuery and getting the ID of the selection drop down (there were two different ID's named after the attribute slug #size & #pa_size).
add_action( 'woocommerce_before_add_to_cart_quantity', 'add_link_on_selection' );
function add_link_on_selection() {
?>
<script>
jQuery(document).ready(function ($) {
$('#size, #pa_size').change(function(){
if($('#add').length) {
$('#add').remove();
return;
} else {
$selection = $(this).val().toLowerCase();
console.log($selection);
$(this).after(
'<div>' +
($selection == 'drum' ? '<div id="add">Freight Restrictions</div>' : '') +
'</div>'
);
}
})
});
</script>
<?php
}

Jquery Autocomplete and MySQL ID Value

hoping someone can help me out with something.
I've got a piece of code which allows the Jquery Autocomplete. What I'm wanting to do is to use the ID(primary key) from my MySQL table and then use that to POST on to another screen.
How would I go about getting the ID into a hidden value from the Jquery code?
Here are my snippets.
Jquery
<script>
$(function() {
$( "#skills" ).autocomplete({
source: 'JQUERYTEST.php'
});
});
</script>
Html
<div class="ui-widget">
<label for="shop">Shopname: </label>
<input id="shop">
</div>
Php/MySQL
<?php
//database configuration
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'aurora';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM shops WHERE shopname LIKE '%".$searchTerm."%'");
while ($row = $query->fetch_assoc()) {
$data[] = $row['shopname'] . ' - '. $row['streetaddress'] . ' - ' . $row['postcode'];
}
//return json data
echo json_encode($data);
?>
Thanks!
Firstly, you will have to use an Ajax call to get the data from the server. So, change your autocomplete function and add an ajax call to receive a response. Then you will have to loop the JSON array in jquery. I have created the id as the whole string with shopname, streetaddress and postcode. Currently, your code doesn't inserts the ID parameter from the database. You can create an id depending on your needs. Then dynamically I have created the HTML and then placed it inside the <div class="ui-widget">
<script>
$( function() {
$( "#skills" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "search.php",
dataType: "jsonp",
data: {
term: request.term
},
success: function( data ) {
var html = "";
$.each(data, function(i, item) {
var arr = item.split('-');
html += "<label for='shop'>Shopname:"+arr[0]+" </label><input id='"+item+"' type='hidden'><br>";
});​
$('.ui-widget').html(html);
}
});
}
});
});
</script>
Try this out. I hope this helps you.

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

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
});

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 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