I want to highlight words i enter in autocomplete search bar - javascript

I want to achieve this in below mention code need
i want to highlight text in auto complete same like pic i added above
<?php
$query = isset($_GET['query']) ? $_GET['query'] : FALSE;
global $wpdb;
// escape values passed to db to avoid sql-injection
$depts = $wpdb->get_results( "SELECT * FROM wp_paklog_service WHERE service_name LIKE '".$query."%'" );
$suggestions = array();
$data = array();
foreach($depts as $row) {
$suggestions[] = $row->service_name;
$data[] = $row->id;
}
json_encode ($suggestions);
?>
//this is js code
var obj = <?php echo json_encode($suggestions); ?>;
jQuery(".search-services").autocomplete({
source: function( request, response ) {
var matcher = new RegExp( "^" + jQuery.ui.autocomplete.escapeRegex( request.term ), "i" );
response( jQuery.grep( obj, function( item ){
return matcher.test( item );
}) );
}

Related

JS populated div content to PHP array without any html tags

I'm trying to pass from a div content populated by JS to a PHP array and inject that array in a wordpress posts loop.
I managed to get an array with the desired values BUT there is an html tag around which is breaking the loop.
I thought that by adding a preg_match_all around that would fix the problem but for some reason the array ends up empty.
I have pasted just below my current state. Currently i'm getting an empty array.
I think this might be coming from the fact that the JS must populate the div after the php has run...
Would any of you have an idea on how to do this? Many thanks in advance. If you need anymore info please do not hesitate.
<?php
$rule = '#<div class="sessionWrongsIDs">(.+?)</div>#';
$content = '<div class="sessionWrongsIDs"></div>';
preg_match_all( $rule, $content, $matches);
print_r( $matches[1] );
$args = array(
'post__in' => $matches[1],
'post_type' => 'qcm'
);
$posts = get_posts( $args );
foreach ( $posts as $p ) : ?>
<?php while( have_posts() ): the_post(); ?>
<?php echo the_title();?><br/>
<?php endwhile; ?>
<?php endforeach; ?>
EDIT 1: Following #FluffyKitten comment, here are some additional info
Using the following:
<?php
$rule = '/<[^>]*>/';
$content = '<div class="sessionWrongsIDs"></div>';
preg_match( $rule, $content, $matches);
print_r( $matches );
?>
The output is:
Array ( [0] =>
1237,1227,1238,1232
And if you inspect that array you can see a div around the values like so:
Array ( [0] =>
<div class="sessionWrongsIDs">1237,1227,1238,1232</div>
To use the array in a wp loop I require a format like so arrray( 1237, 1227, 1238, 1232 )
EDIT 2: Following #jibsteroos comment, about strip_tags(). The following is returning nothing. Probably because the <div class="sessionWrongsIDs"></div> content is javascript generated.
<?php
$rule = '/<[^>]*>/';
$content = '<div class="sessionWrongsIDs"></div>';
preg_match( $rule, $content, $matches);
print_r( strip_tags( $matches[0] ) );
?>
EDIT 3: Following #FluffyKitten 2nd comment, here is the JS side. I'm using local storage to save the post ID and display it in a hidden div on the frontend. My thaught was to use the generated content (posts IDs) to generate a new query. But i've not been able to do it successfully .
$( document ).ready( function () {
var sessionWrongsIDs = [];
for ( i = 0; i < window.localStorage.length; i++ ) {
keys = window.localStorage.key( i );
if ( keys.slice( 0, 3 ) === 'QCM' ) {
sessionWrongsIDs.push( JSON.parse( window.localStorage.getItem( keys ) ) );
$( '.sessionWrongsIDs' ).html( sessionWrongsIDs.join( ',' ) );
};
};
$( 'input[name=answSel]:radio' ).click( function() {
if ( $( 'input[name=answSel]:checked' ).val() == 0 ) {
var sessionWrongsIDs = [];
localStorage.setItem( $( '.currentTitle' ).html(), $( '.currentID' ).html() );
for ( i = 0; i < window.localStorage.length; i++ ) {
keys = window.localStorage.key( i );
if ( keys.slice( 0, 3 ) === 'QCM' ) {
sessionWrongsIDs.push( JSON.parse( window.localStorage.getItem( keys ) ) );
$( '.sessionWrongsIDs' ).html( sessionWrongsIDs.join( ',' ) );
};
};
};
} );
} );

button radio wont stay checked after update Wordpress

I m trying to implement query with custom fields on my local wordpress website.
All works like a charm except when I check the radio button, this one want to be checked...
Can you help me please ? thanks for your reply.
<div id="archive-filters">
<?php foreach( $GLOBALS['my_query_filters'] as $key => $name ):
$field = get_field_object($key);
if( isset($_GET[ $name ]) ) {
$field['value'] = explode(',', $_GET[ $name ]);
}
// create filter
?>
<div class="filter" data-filter="<?php echo $name; ?>">
<?php create_field( $field ); ?>
</div>
<?php endforeach; ?>
</div>
<script type="text/javascript">
(function($) {
// change
$('#archive-filters').on('change', 'input[type="radio"]', function(){
var url = '';
args = {};
$('#archive-filters .filter').each(function(){
var filter = $(this).data('filter'),
vals = [];
$(this).find('input:checked').each(function(){
vals.push( $(this).val() );
});
// append to args
args[ filter ] = vals.join(',');
});
// update url
url += '?';
// loop over args
$.each(args, function( name, value ){
url += name + '=' + value + '&';
});
// remove last &
url = url.slice(0, -1);
// reload page
window.location.replace( url );
});
})(jQuery);
</script>

How to convert a JSON to an array which can be used to bind values in a dropdown list?

I have an application where I can generate JSON, which in turn I use as input to GoogleCharts API to draw different visualizations. The pages of this web application are in HTML.
Suppose I have a JSON which has a list of departments of a hospital, like: [{"v":"General Medicine"},{"v":"Laboratory"}]
How do I use Javascript to convert this to an array which in turn can be used as option values of a drop down list?
I am using the following code to generate JSON:
<?php
$serverName = "forestroot"; //serverName\instanceName
$connectionInfo = array( "Database"=>"****", "UID"=>"****", "PWD"=>"****");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
//echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT distinct([DEPT_NAME]) as dept FROM [Pristine11Dec15].[dbo]. [PACKAGE_REVN]";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$result = sqlsrv_query( $conn, $sql, $params, $options);
if (sqlsrv_num_rows( $result ) > 0) {
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$array[] = array('v'=>$row["dept"]);
}
}
echo json_encode($array);
sqlsrv_close( $conn);
?>
The output is [{"v":"General Medicine"},{"v":"Laboratory"}]
When I use JSON.parse in my code I am getting the options as [object Object] in the drop down list. Where am I going wrong?
var json = '[{"v":"General Medicine"},{"v":"Laboratory"}]';
Parse the data and use map to return an array of v values:
var list = JSON.parse(json).map(function (el) {
return el.v;
}); // [ "General Medicine", "Laboratory" ]
DEMO
You could extend this however to build up the HTML for the select:
var templ = '<option value="#{el}">#{el}</option>';
var options = JSON.parse(json).map(function (el) {
return templ.replace('#{el}', el.v, 'g');
}).join('');
var select = '<select>' + options + '</select>';
document.getElementById('menu').insertAdjacentHTML('beforeend', select);
DEMO

City search jquery script with json list

I have a jquery script that works with a city search field
Script
<script type="text/javascript">
$(document).ready(function()
{
var ac_config =
{
source: "demo_cities.php",
select: function(event, ui)
{
$("#City").val(ui.item.City);
$("#Country").val(ui.item.Country);
$("#DestinationId").val(ui.item.DestinationId);
},
minLength:3
};
$("#City" ).autocomplete(ac_config);
});
</script>
and php code is
<?php
$cities= array(
array('City'=>'Barcelona',
Country=>'SP',
DestinationId=>'10001'),
....... );
$term = trim(strip_tags($_GET['term']));
$matches = array();
foreach($cities as $City)
{
if(stripos($City['City'], $term) !== false)
{
$City['value'] = $City['City'];
$City['label'] = "{$City['City']}";
$matches[] = $City;
}
}
$matches = array_slice($matches, 1, 7);
print json_encode($matches);
?>
How can i make the script to search only by the first 3 charachers from the City name
In your PHP code, you're looking for a city that contains a string in city name. If you want to show cities that starts with specific chars, you could use substr
<?php
$cities= array(
array('City'=>'Barcelona',
'Country'=>'SP',
'DestinationId'=>'10001'
),
//more cities ...
);
$term = strtolower(trim(strip_tags($_GET['term'])));
$matches = array();
foreach($cities as $City)
{
if(strtolower(substr($city['city'], 0, strlen($term))) == $term)
{
$City['value'] = $City['City'];
$City['label'] = "{$City['City']}";
$matches[] = $City;
}
}
$matches = array_slice($matches, 1, 7);
print json_encode($matches);
?>
normally city will not change its name, so I put city name in a js file, then let FE to do search,
and autocomplete part seems no question.

Can jQuery UI Autocomplete use values from multiple input fields

I've been struggling with this code for a while and honestly I'm stuck.
This is how my auto-complete script looks like:
jQ19(function(){
// minLength:1 - how many characters user enters in order to start search
jQ19('#location_name').autocomplete({
source:'adress.php',
minLength:2,
select: function(event, ui){
// just in case you want to see the ID
var accountVal = ui.item.value;
console.log(accountVal);
// now set the label in the textbox
var accountText = ui.item.label;
jQ19('#location_name').val(accountText);
return false;
},
focus: function( event, ui ) {
// this is to prevent showing an ID in the textbox instead of name
// when the user tries to select using the up/down arrow of his keyboard
jQ19( '#location_name' ).val( ui.item.label );
return false;
}
});
});
Some more js to get me the additional value:
<script type='text/javascript'>
$('#city').on( 'change', function () {
var x = document.getElementById('city').value;
$.ajax({
type: 'post',
url: 'http://localhost/profsonstage/account/_compettions/autocomplate/location_name.php',
data: {
value: x
},
success: function( data ) {
console.log( data );
}
});
});
</script>*/
And the php that fetches the data results:
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}
// get the search term
$city = $_GET['city'];
$b = explode(" ",$city); //get rid of the city code
$a =$b[0];
$search_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : "";
//query to search for data
$query = "SELECT * from locations where adress like '%$search_term%' and city=='$a'
LIMIT 0 , 5";
The problem is when the user types a value in the input for the #City the query looks like this:
$query = "SELECT * from locations where adress like '%%' and
city=='SomeCity'
LIMIT 0 , 5";
and when we go to the next input that (is supposed to be autocomplete too and start typing) the query looks like
$query = "SELECT * from locations where adress like '%input to autocomplate%' and
city==''
LIMIT 0 , 5";
Basically I can't figure out a way to pass the values at the same time. Any help will be appreciated.
You can use following;
jQ19(function(){
// minLength:1 - how many characters user enters in order to start search
jQ19('#location_name').autocomplete({
minLength:2,
select: function(event, ui){
// just in case you want to see the ID
var accountVal = ui.item.value;
console.log(accountVal);
// now set the label in the textbox
var accountText = ui.item.label;
jQ19('#location_name').val(accountText);
return false;
},
source: function( request, response ) {
var term = request.term;
$.getJSON( "address.php?term=" + term + "&city=" + $("#city").val(), request, function( data, status, xhr ) {
response( data );
});
},
focus: function( event, ui ) {
// this is to prevent showing an ID in the textbox instead of name
// when the user tries to select using the up/down arrow of his keyboard
jQ19( '#location_name' ).val( ui.item.label );
return false;
}
});
});
And in your php file;
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}
// get the search term
$city = $_GET['city'];
$b = explode(" ",$city); //get rid of the city code
$a =$b[0];
$search_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : "";
//query to search for data
$query = "SELECT * from locations where adress like '%$search_term%' and city=='$a'
LIMIT 0 , 5";
//Fetch your data and respond json

Categories

Resources