Predictive Dropdown Input - javascript

I have a table called contacts, where each user stores the username of his contacts:
$result = mysql_query("SELECT * FROM contacts WHERE sender='".$_SESSION ["username"]."'");
$row = mysql_fetch_array($result);
My page is used to compose a message to an user. So when a user types in the textfield I need to show a dropdown list matching names from his contacts (as in Gmail).
<input name="reciever" type="text" value="" class="inputs3" placeholder="Enter the username"/>
I searched a lot, but couldn't find any working script.

Take a look at this auto complete sample, Demo / JSFiddle
autocomplete({
minLength: 1,
source: function( request, response ) {
//check if the request string starts with a space
if(request.term===' ')
{
response([{value: "Enter Some text to search"}]);
return false;
}
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
}
This will give autocomplete coding idea

Related

fetch db mysql value in search input field and modifying in dropdown

I cannot find a solution for my problem because for me it is an advanced level of programming.
I have a custom search field, but I need to 'convert it' in a dropdown menu that fetching some users values in mysql, avoiding writing hundreds of selection options.
This is the registration form field Im working it
<tr class="user-luogo-wrap">
<th><label for="luogo">
Luogo: </label></th>
<td><input type="text" name="luogo" id="luogo" value="Treviso" class="regular-text"></td>
</tr>
Created with a function
function my_user_contactmethods( $user_contactmethods ){
$user_contactmethods['luogo'] = 'Luogo:';
return $user_contactmethods;
}
add_filter('user_contactmethods', 'my_user_contactmethods', 5);
and this is the field where I need to fetch the 'luogo' mysql values and modifying it in dropdown
<div class="um-search-filter um-text-filter-type "> <input type="text" autocomplete="off" id="luogo" name="luogo" placeholder="Luogo" value="" class="um-form-field" aria-label="Luogo"></div>
I hope I have explained it well. Can someone help me?
In Console I have found the Form data , Request payload generated after a search action:
directory_id=3f9fc&page=1&search=&sorting=display_name&gmt_offset=8&post_refferer=61&nonce=f47827a450&luogo=boston&action=um_get_members
So Im trying to modify this function
function field_choices( $field ) {
// reset choices
$field['luogo'] = array();
// get the textarea value from options page without any formatting
$choices = get_field('my_select_values', 'option', false);
// explode the value so that each line is a new array piece
$choices = explode("\n", $choices);
// remove any unwanted white space
$choices = array_map('trim', $choices);
// loop through array and add to field 'choices'
if( is_array($choices) ) {
foreach( $choices as $choice ) {
$field['luogo'][ $choice ] = $choice;
}
}
// return the field
return $field;
}
add_action('um_get_members', 'field_choices');
Is my intuition correct?

Issues with search bar filter, using JS/JQuery in laravel blade template

I have a blade template with a search bar, which has no submit button and is used for filtering. However, I can't seem to get it to filter appropriately, as the page was originally using angular (which has been removed completely).
My page displays all of my products using foreach loops and displays the info from variables in my page controller (pulling everything from the database and storing as variables). Anyway, everything displays fine but I need help getting this to filter properly.
Basically, if a term entered in the search bar is anywhere in the JSON object gathered by the controller, then I want it to only display those objects. I may even need another foreach loop.
Here's the html/blade code:
<!--Search bar div-->
<div class="uk-width-5-10">
<div class="md-input-wrapper search-form">
<form id="searchProducts">
<input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>
<span class="md-input-bar"></span>
</form>
</div>
<!--foreach loops around the wrapper that shows products, for reference-->
#foreach ($orderFormData->pgroups as $pgroup)
#foreach ($pgroup->image_names as $image_name)
#foreach ($pgroup->pskus as $psku)
Javascript for the search (see the variable for the JSON object, that's what I need to search within)
<script>
var orderFormData = <?php echo json_encode ($tempdata);?>;
</script>
<script>
var orderData = orderFormData // default value
var search = function (e) {
var term = e.currentTarget.value
orderData = Object.entries(orderFormData).reduce(function (data, entry) {
if (entry[0].match(term) || entry[1].match(term)) {
data[entry[0]] = entry[1]
}
return data
}, {})
console.log(orderData)
}
document.querySelector('#srch-term').addEventListener('keyup', search)
</script>
Is there a better way I should be doing this? I may even need to do a foreach loop around the search bar
It kind of sounds like you're looking for an auto complete. Have you looked at the jquery-ui-autocomplete library? It's pretty easy to implement, and might add more functionality more easily than writing loops yourself.
https://jqueryui.com/autocomplete/
I'll get into why I named the function below, but here's my implementation:
monkeyPatchAutocomplete();
$("#your_searchbox_selector").autocomplete({
source: // http://Your_Search_URL_endpoint_here,
delay: 500, // prevents search from running on *every* keystroke
minLength: 1, // default is 2, change or remove as you like
// open page after selecting (with enter key).
select: function( event, ui )
{
var qval = ui.item.id // this pulls whatever field you're looking for in your JSON that you want to use to direct your user to the new page, in my case "id";
var url = 'http://whereever_you_want_your_user_to_go?';
window.location = url + qval;
}
});
For my implementation, I wanted to color code the results in my autocomplete list with active and inactive entries, so my search controller JSON result includes 3 fields:
'value' => $searchable_values, 'id' => $id_mapping_of_whatever, 'class' => $css_classes_to_use
My search controller plugs in emails, names, and phone numbers to the value field, which is searchable, then maps an id, and plugs in css classes that I use to change the text color of the results through a monkeypatch on jQuery's autocomplete:
function monkeyPatchAutocomplete()
{
$.ui.autocomplete.prototype._renderItem = function( ul, item)
{
var re = new RegExp(this.term, 'i');
var t = item.label.replace(re,"<span class='autocomplete-span'>" + this.term + "</span>");
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a class='text-" + item.class + "'>" + t + "</a>" )
.appendTo( ul )
};
};
If you're interested in formatting your results, check out dev.e.loper's answer to: How can I custom-format the Autocomplete plug-in results?.

Taging and conditional autocomplete

I'm using http://aehlke.github.io/tag-it/ for taging and autocomplete. As of right now, I can autocomplete for a single term:
Console:
GET .../source.php?term=value01
Javascript:
$("#input-newsearch-2").tagit({
singleField: true,
singleFieldDelimiter: ",",
allowSpaces: true,
autocomplete: ({
source: function( request, response ) {
//var tagterm = $('#input-newsearch-2').val();
$.ajax({
url: "source.php",
dataType: "json",
data: {
//term: tagterm
//term: $('#input-newsearch-2').val()
term: request.term
},
//data: JSON.stringify({ term: $('#input-newsearch-2').val() }),
success: function( data ) {
response( data );
}
});
console.log( request.term );
},
minLength: 3,
select: function(event,ui){
}
})
});
... when hitting key enter the value gets tagged ( alert($('#input-newsearch-2').val() = value01) ) and I can search for the next term.
But when entering the next term, autocomplete searches the whole database each time again. I would like to filter the database considering the previous tags (AND WHERE)? How is this possible?
This is my html:
<input id="input-newsearch-2" autocomplete="off" type="text">
// created by tagit
<ul class="tagit ui-widget ui-widget-content ui-corner-all">
<li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
<li class="tagit-new">
<input class="ui-widget-content ui-autocomplete-input" autocomplete="off" type="text">
</li>
</ul>
... when I've tagged multiple values #input-newsearch-2 looks like:
$('#input-newsearch-2').val() = value01,value02,value03
Do you mean, you want to concatenate the new entered value to the previous entered value(s)?
You could concatenate the new entry to a globally declared variable.
// before/outside of tagit()...
var terms="";
If the global variable has a length>0, then add a comma then the new entry, otherwise don't add the comma.
// concatenate when you wish:
if(terms.length>0){
terms+=',';
}
$terms+=$('#input-newsearch-2').val();
Then just add the global variable to ajax's data object, and the csv string should be delivered.
data: {
term: terms
},
Alternatively, you could concatenate new entries to an <input name="termstorage" type="hidden" value=""> element, and just have your ajax's collect that value.
I suppose in either instance, you'd also want to offer the ability to clear previous entries from memory.
Here is the php query build part...
I am making the assumption from your other recent/associated question that you are filtering against db columns: name & code
Also, any values entered by the user containing a comma will impact the query. Always, always sanitize user input.
This code uses a loop purely to demonstrate how three different inputs will generate different queries. The loop will not be necessary in your actual case since your input is a single string.
Code: (Demo)
$mock_GET_term[]="";
$mock_GET_term[]="value01";
$mock_GET_term[]="value01,value02,value03";
foreach($mock_GET_term as $csv){
$query="SELECT * FROM `accounts`";
if(strlen($csv)>0){
$where_cond=str_replace(',',"%' OR `name` LIKE '%",$csv);
$query.=" WHERE (`name` LIKE '%{$where_cond}%'";
$query.=" OR `code` LIKE '%{$where_cond}%')";
}
echo "Query = $query\n\n";
}
Output:
Query = SELECT * FROM `accounts`
Query = SELECT * FROM `accounts` WHERE (`name` LIKE '%value01%' OR `code` LIKE '%value01%')
Query = SELECT * FROM `accounts` WHERE (`name` LIKE '%value01%' OR `name` LIKE '%value02%' OR `name` LIKE '%value03%' OR `code` LIKE '%value01%' OR `name` LIKE '%value02%' OR `name` LIKE '%value03%')

Case-insensitive autocomplete in Javascript

I have a javascript code that is used for autocomplete functionality. It highlights the text that is entered in a search box and matches it with the text in a database. This is case-sensitive, so it only highlights the text which is in the database table. I want the search to be case-insensitive.
This is my existing code:
<script type="text/javascript">
$(function() {
var availableTags = [<?php echo $tagsString; ?>];
$( "#tags" ).autocomplete({
source: availableTags
});
});
$.extend( $.ui.autocomplete.prototype, {
_renderItem: function( ul, item ) {
var term = this.element.val(),
html = item.label.replace( term, "<span class='f1'>$&</span>" );
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( $("<a></a>").html(html) )
.appendTo( ul );
}
});
</script>
in your database code use LOWER on both sides of the equasion.
... WHERE LOWER(db_field) = LOWER(:text) ...
Or you can cast the input to lower before giving it to the database and omit the right LOWER in this case
In case of LIKE
... WHERE LOWER(db_field) like '%' || LOWER(:text) || '%' ...
Please always quote properly or better use perpared statements to prevent SQL injections.
EDIT: Found a cleaner way using only bindings without quoting
I assume you are using MySQL.
You can lower field name and searched value,
WHERE LOWER( db_table.db_field ) = LOWER(:text) // find exact match
or use like with lower:
WHERE LOWER( db_table.db_field ) LIKE '%' || LOWER(:text) || '%' // find all that have this text as substring
But in boh cases remember to use parametrized statemenets, in order to avoid SQL injection atacks.

text field autopopulate from database using javascript

I want to get data from database to text field by using autopopulate when i type data in text field using javascript can any one help to me please
One of the way to solve that is for instance to use autocomplete control from jquery.ui and create service using language/server of your choose to get data from your db.
Configuring jquery.ui autocomplete is as simple as
var availableOptions = ["apple", "pear", "pineapple"]
$( "#auto" ).autocomplete({
source: availableOptions
});
just having input control
<div>
<label for="auto">Fruits: </label>
<input id="auto" />
</div>
So if you dont have thousands of data items above is one of the easiest ways.
Alternatively, having implemented web service you can query it ajax-style, configuring autocomplete plugin right way
$('#auto').autocomplete({
source: function( request, response ) {
$.getJSON( "/api/search", {
term: request.term
}, response );
},
search: function() {
var term = this.value
if ( term.length < 2 ) {
return false;
}
}
})

Categories

Resources