I have been coding around with Google Geocoding until I found out that the Geocoding API may only be used in conjunction with a Google map. That is inconvenient because I don't need to display a map. So I switched to Geonames which is awesome!
I get the latitude and longitude of an address and add them to my database.
The code below is Jquery for a text input where users add their city/town and an auto-complete appears presuming the city they are typing. It works great but I also want to add the latitude and longitude of their city in 2 hidden form fields for sending to the database.
How is it possible to retrieve those coordinates from Geonames?
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).attr( "scrollTop", 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
The lat & lng are being returned; see this test request:
http://api.geonames.org/searchJSON?style=full&maxRows=12&name_startsWith=romse&username=demo
It is in the structure below so you just need to access it:
{ "geonames" : [ {
"adminCode1" : "ENG",
<SNIP>
"geonameId" : 2639189,
"lat" : 50.989057046475203,
"lng" : -1.4998912811279297
Related
I have this live search and it works perfectly. What i want to do is I want to get another field. Aside of fetching indcator name i also want to get its ID by assigning it to another input type once I clicked the indicatorname using live search.
Heres the Script :
<script type="text/javascript">
$(document).ready(function() {
$('#indicatorname').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'indicatorname'
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
selectFirst: true,
minLength: 0,
focus : function( event, ui ) {
$('#indicatorname').html(ui.item.value);
},
select: function( event, ui ) {
$('#indicatorname').html(ui.item.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top");
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
$('#slider').rhinoslider({
effect: 'transfer'
});
});
</script>
Heres the ajax.php :
<?php
$connection = pg_connect("host=localhost dbname=brgy_profiler
user=postgres password=password");
if (!$connection)
{
echo "Couldn't make a connection!";
}
?>
<?php
if($_GET['type'] == 'indicatorname'){
$result = pg_query("SELECT cindicatordesc,nindicatorid from
tbl_indicators where cindicatordesc LIKE
'%".$_GET['name_startsWith']."%'");
$data = array();
while ($row = pg_fetch_array($result))
{
array_push($data, $row['cindicatordesc']);
}
echo json_encode($data);
}
?>
Here's my tbl_indicator :
How can i get also the nindicatorid field and get it together with cindicatordesc using ajax live search?
Note: Only cindicatordesc will be displayed and nindicatorid will be save in an input type.
Not a problem. You can add additional data attributes in your Auto-complete select return as,
$('#indicatorname').autocomplete({
source: function( request, response ) {
...........
success: function( data ) {
response( $.map( data, function( itemList ) {
return {
label: itemList.label,
value: itemList.value,
extraField : itemList.extraField
}
}));
So, Only change you need to accommodate is the Server side where you need to send the extra values to the Auto-complete AJAX.
And , On select event you can fetch the value as ui.item.extraField.
Here is a Sample Demo of using multiple attributes. Although it is not same as you have done, the inner logic is the same.
I'm using this jquery plugin : JQuery Autocomplete. Problem I'm getting json data but it's not appearing on the autocomplete list.
The JQuery code:
$( "#student-id" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/ajax_admin.php?auto_student=" + $( "#student-id" ).val(),
dataType:"json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.students, function( item ) {
return {
label: item.id +" , "+ item.name,
value: item.id
}
}));
}
});
},
minLength: 2,
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
The PHP Script is :
public function load_ajax_student_list($val)
{
$val = "%".$val."%";
$stmt = $this->conn->prepare("select * from student where studentAiubId like :value limit 0,5");
$stmt->bindValue(':value', $val);
$stmt->execute();
if($stmt->rowCount() < 1)
echo "";
else
{
$result = $stmt->fetchAll();
$output = array();
foreach($result as $row)
{
if($row['mname']=="")
$name = $row['fname']." ".$row['lname'];
else
$name = $row['fname']." ".$row['mname']." ".$row['lname'];
$data["name"] = $name;
$data["id"] = $row['studentAiubId'];
$output["students"][] = $data;
}
echo json_encode($output);
}
}
If the call goes like this: ajax/ajax_admin.php?auto_student=10
The produced data from PHP script is :
{
"students": [
{"name":"Moh Mamun Sardar","id":"10-15987-1"},
{"name":"Rehan Ahmed","id":"10-12451-2"},
{"name":"Abid Hassan","id":"10-15412-1"},
{"name":"Abir Islam","id":"10-11245-1"}
]
}
But Nothing showing on autocomplete. What I'm doing wrong?
try something like this
$.map( data.students, function(item ) {
return {
label: item.name,
value: item.id
});
it is minlength not minLength see casing
You have forgotten the "appendTo" property. In this propery you have to specify the selector of the element you wish the information to be appended to like this
appendTo: '.class' or appendTo: '#id'
You have to add this property to the initialization of the autocomplete as a sibling of source and etc ...
I am trying to make auto complater working in wordpress.
Here is my php code
function autocompleteCallback() {
global $wpdb; // this is how you get access to the database
//$whatever = $_POST['search_string'];
$name=$_POST['search_string'];
// echo'hiii'. $name='a';
$employee=$wpdb->get_results("SELECT `user_login` FROM wp_users WHERE user_login LIKE '$name%' ");
foreach($employee as $key=> $value){
$myarr[]=array('val' => $value->user_login);
}
//wp_reset_query();
echo json_encode($myarr);
die(); // this is required to return a proper result
}
add_action('wp_ajax_autocompleteCallback', 'autocompleteCallback');
add_action('wp_ajax_nopriv_autocompleteCallback', 'autocompleteCallback');
Here is my jquery
$(function() {
//function log( message ) {
// $( "<div>" ).text( message ).prependTo( "#log" );
// $( "#log" ).scrollTop( 0 );
// }
//alert('huii');
$("#se").autocomplete({
//dataType: "json",
source: function( request, response ) {
$.ajax({
url: './wp-admin/admin-ajax.php',
dataType: "json",
data: {
action: 'autocompleteCallback',
search_string:'a',
// term: $(options.fieldName).val()
},
success: function( data ) {
//alert(data);
alert('huii');
response( $.map( data.results, function( item ) {
return {
alert('hi');
label: item.val,
///value: item.title,
//url: item.url
}
}));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}
});
},
minLength: 1,
//select: function( event, ui ) {
// log( ui.item ?
// "Selected: " + ui.item.value + " aka " + ui.item.id :
// "Nothing selected, input was " + this.value );
// }
// select: function( event, ui ) {
// log( ui.item ?
// "Selected: " + ui.item.value + " aka " + ui.item.id :
// "Nothing selected, input was " + this.value );
// }
});
});
However, I could make this work in normal html, php web site where I passe source as a string. I can't figure where I have done mistake when I use function for source tag.
html code
<input id ="se" type="text" name="test" width="20" />
Why you dont just use this awesome plugin: SearchAutocomplete
The jQuery:
$("[type=text]").autocomplete({
source: "json.php",
minLength: 0
}).addClass("ui-widget ui-widget-content ui-corner-left");
Works fine if I change the source: to a JS array. I know that the php is working because I can see it in the console, but here is the sample php anyways:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
So the dropdown just isn't displaying. Feeling pretty stupid right about now.
In your json.php file, be sure to set the content encoding to be json via the header() function before your echo. This way jQuery should see the array as proper json.
header("Content-Type: application/json");
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
A few days ago I was also having problems with a JSON-populated Autocomplete.
My problem was that I wasn't setting the content-type, as Wally said above:
header("Content-Type: application/json");
I also wrapped my jQuery autocomplete call inside a getJSON, then used the data from that function to populate the autocomplete field. My gut tells me that the extra getJSON shouldn't be necessary, but like you, I was having problems referencing my PHP file as the source.
$.getJSON("json.php", function(data) {
$("[type=text]").autocomplete({
dataType: "json",
source: data,
minLength: 1,
});
});
Since I'm using an old PHP version, I hand-made my JSON. I included "label" and "value" fields because I'm fairly certain they're necessary for the autocomplete to work.
$jsonList = "[{"label" : "Item 1", "value" : "1"}, {"label" : "Item 2", "value" : "2"}]";
return $jsonList;
http://jqueryui.com/demos/autocomplete/remote-jsonp.html
Check this get from demos site.
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
I have this problem with the jQuery autocomplete.
I use JSON data, retrieved from a mySQL db, by PHP function.
$.ajax({
dataType: 'json',
async: false,
method: 'post',
success: function(data) {
test = data;
},
url: '<?php echo site_url('products/autocomplete/'); ?>'
});
So, my JSON data is stored into the variable: 'test'.
This is my autocomplete code:
$( "#prodname" ).autocomplete({
minLenght: 2,
source: test,
focus: function( event, ui ) {
$( "#prodname" ).val( ui.item.prodname );
return false;
},
select: function( event, ui ) {
$( "#prodname" ).val( ui.item.prodname );
$( "#uname" ).val( ui.item.uname );
$( "input[name=prodname_fk]" ).val( ui.item.id );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.prodname + "</a>" )
.appendTo( ul );
};
The data loads properly and all, but the autocomplete field doesn't seem to work properly. The first item of my JSON object starts with 'b', so only when I press the letter 'b', the autocomplete(suggestions) appear.
How can I fix this? My guess is maybe because I use async: false, but that the only way I made it work a little at first place.
I need the autocomplete on my Product field, so when a user selects product, a hidden field (prodname_fk) receives the corresponding ID of the product. And the uname field (unit of measure) is only used for displaying purposes.
I attach picture for your reference.
Thank you in advance.
If your php page returns json, you can put its url directly in the autocomplete function :
<script>
$(function() {
$( "#birds" ).autocomplete({
source: '<?php echo site_url('products/autocomplete/'); ?>',
minLength: 2,
select: function( event, ui ) {
$( "#prodname" ).val( ui.item.prodname );
$( "#uname" ).val( ui.item.uname );
$( "input[name=prodname_fk]" ).val( ui.item.id );
}
});
});
</script>
In your script, you can remove the _renderitem replacement, as it's only useful if you want specific rendering, like
'<em>' + item.prodname + '</em>(' + item.id ')'
You should try to adapt the basic samples from http://jqueryui.com/demos/autocomplete/#remote then add more advanced functionality.
This is how I made it work.
$( "#prodname" ).autocomplete({
minLenght: 2,
source: "<?php echo site_url('products/autocomplete/'); ?>",
select: function( event, ui ) {
$( "#prodname" ).val( ui.item.prodname );
$( "#code" ).val( ui.item.code );
$( "#uname" ).val( ui.item.uname );
$( "input[name=prodname_fk]" ).val( ui.item.id );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.prodname + "</a>" )
.appendTo( ul );
};
Now, I use asynchronous search, so whenever the user types something in the Products field, a GET request is sent, with the term (http://localhost/ci/products/autocomplete?term=xxx), which is searched against the product names into the database, returning the matching results(JSON) into the autocomplete suggestion box.