City search jquery script with json list - javascript

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.

Related

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>

Autocomplete Multiple Values in Codeigniter

I have problem with autocomplete in Codeigninter and Jquery
I have a controller
<?php
public function search() {
$user = $_GET['term'];
$query = $this
->db
->select('nama_kota')
->like('nama_kota', $user)
->get('kota');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$row_set[] = htmlentities(stripslashes($row['nama_kota']));
}
echo json_encode($row_set);
}
}
?>
I have a view
<script>
$(function () {
var availableTags = "<?php echo base_url('admin/kota/search'); ?>";
$("#user-input").autocomplete({
source: availableTags
});
});
</script>
<input id="user-input" type="text" name="nama_kota" placeholder="Search User" autocomplete="on">
everything its okay
but I'm trying multiple values
<script>
$(function () {
var availableTags = "<?php echo base_url('admin/kota/search'); ?>";
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#user-input").autocomplete({
minLength: 0,
source: function (request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
</script>
<input id="user-input" type="text" name="nama_kota" placeholder="Search User" autocomplete="on">
no work and availableTags only read addres url no function in controller
whats wrong guys please help me, Thanks
which type off output you need If you need like this
eg.
name,
address,
blood_group.
with output of Autocomplete call
Sorry For late reply I am very very busy in my work
this is JS call to Controller
<script>
jQuery("#h_student_name").autocomplete({
minLength: 0,
source: "DropdownController/hostel_students/" + $("#h_student_name").val(),
autoFocus: true,
scroll: true,
dataType: 'jsonp',
select: function (event, ui) {
jQuery("#h_student_name").val(ui.item.contactPerson);
jQuery("#h_student_id").val(ui.item.code);
}
}).focus(function () {
jQuery(this).autocomplete("search", "");
});
</script>
and this is controller for call
<?php
//Hostel Student Auto compelete
public function hostel_students(){
$term = trim(strip_tags($this->input->get('term')));
if( $term == ''){
$like = $term;
$result_set = $this->DropdownModel->hostel_students(array('hostel_status_id' => 1));
$labels = array();
foreach ($result_set as $row_set) {
$labels[] = array(
'label' => $row_set->student_name.' S/D '.$row_set->father_name.' ,Form# '.$row_set->form_no.' ',
'code' => $row_set->hostel_id,
'value' => $row_set->student_name,
);
}
$matches = array();
foreach($labels as $label){
$label['value'] = $label['value'];
$label['code'] = $label['code'];
$label['label'] = $label['label'];
$matches[] = $label;
}
$matches = array_slice($matches, 0, 10);
echo json_encode($matches);
} else if($term != ''){
$like = $term;
$result_set = $this->DropdownModel->hostel_students(array('hostel_status_id' => 1), $like);
$labels = array();
foreach ($result_set as $row_set) {
$labels[] = array(
'label' => $row_set->student_name.' S/D '.$row_set->father_name.' ,Form# '.$row_set->form_no.' ',
'code' => $row_set->hostel_id,
'value' => $row_set->student_name,
);
}
$matches = array();
foreach($labels as $label){
$label['value'] = $label['value'];
$label['code'] = $label['code'];
$label['label'] = $label['label'];
$matches[] = $label;
}
$matches = array_slice($matches, 0, 10);
echo json_encode($matches);
}
}
?>
and this is model for call
<?php
// Hostel student autocomplete
public function hostel_students($where, $like = NULL){
if($like):
$this->db->like('student_name', $like);
$this->db->or_like('form_no', $like);
$this->db->or_like('college_no', $like);
endif;
$this->db->join('student_record', 'student_record.student_id=hostel_student_record.student_id');
return $this->db->where($where)->get('hostel_student_record')->result();
}
}
?>
have any issue comment me I will online today

I want to highlight words i enter in autocomplete search bar

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

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

JSON get form values using AJAX

I dont know if i am tired or why i cannot get it right please help what i need is
<script language="javascript">
$(document).ready(function(){
getResultsCountry();
})
function getResultsCountry() {
$.ajax({
url:'suggest_country.html',
type:'POST',
data: 'q=',
dataType: 'json',
success: function( json ) {
$('#country')[0].options.length = 0;
$.each(json, function(i, value) {
if (value=='<?php echo $country; ?>') {
$('#country').append($('<option>').text(value).attr('value', value).attr('selected', 'selected'));
} else {
$('#country').append($('<option>').text(value).attr('value', value));
};
});
}
});
};
</script>
Code in external file looks like
<?php
$results = mysql_query('SELECT DISTINCT country FROM MyTable WHERE country LIKE \'%\' ORDER BY country');
while( $result = mysql_fetch_array($results) ) {
$cities = $cities.' short = \''.$result['country'].'\' OR';
}
$cities = substr($cities, 1,strlen($cities)-3);
$results2 = mysql_query('SELECT full, short FROM `Countries` WHERE '.$cities);
$json = array();
while( $result2 = mysql_fetch_array($results2) ) {
$json[] = $result2['short'].','.$result2['full'];
}
echo json_encode( $json );
mysql_close($db2);
?>
Response i am getting is
["AG,ANTIGUA AND BARBUDA","AU,AUSTRALIA","BR,BRAZIL","CA,CANADA","KY,CAYMAN ISLANDS","CN,CHINA"]
What i need is to fill it in the options for tag i got this part too, but i cannot make it fill country code AG as value and name as name like
<option value="AG">Antigua</option>
please break it down for me i am really confused and tired its been hours of headache.
You need to split values
$.each(json, function(i, value) {
var arr_values = value.split(',');
if (value=='<?php echo $country; ?>') {
$('#country').append($('<option>').text(arr_values[1]).attr('value', arr_values[0]).attr('selected', 'selected'));
} else {
$('#country').append($('<option>').text(arr_values[1]).attr('value', arr_values[0])));
};
});
It would make your ajax callback much easier if you didn't have to split your strings..
while( $result2 = mysql_fetch_array($results2) ) {
$json[] = array('short'=>$result2['short'],
'full' => $result2['full']
);
}
And then you can parse by
$.each(json, function(i, value) {
if (value['full']=='<?php echo $country; ?>') {
$('#country').append($('<option>').text(value['full']).attr('value', value['short']).attr('selected', 'selected'));
} else {
$('#country').append($('<option>').text(value['short']).attr('value', value['full'])));
};
});

Categories

Resources