Google Maps info window not displaying on first mouse over - google-maps

I have a Google map that pulls data from a database. Everything works like it's supposed to, except for the info window that pops up when you mouse over a certain point on the map (this point is part of a set that gets pulled from a database. So there can be any number of points at any given stage).
My code looks like this:
function getwindow(id) {
if(infowindows[id] == null || infowindows[id] == '') {
$.ajax({
url: "view/"+id,
type: "post",
async: true,
beforeSend: function() {
},
success: function(data) {
data = JSON.parse(data);
if(data.success) {
infowindows[id] = '<b>Info For: </b>' + data.Clinic.official_clinic_name + '<br/>' +
'{{image}}<br/>' +
'Tel: ' + data.Clinic.telephone;
} else {
alert('error');
}
}
});
}
}
var infowindow = new google.maps.InfoWindow({
content: ''
});
<?php foreach($jsdata as $data) : ?>
infowindows[<?php echo $data['id'];?>] = '';
google.maps.event.addListener(marker_<?php echo $data['id'];?>, 'mouseover', function() {
getwindow(<?php echo $data['id'];?>);
infowindow.setContent(infowindows[<?php echo $data['id'];?>]);
infowindow.open(map,marker_<?php echo $data['id']?>);
});
google.maps.event.addListener(marker_<?php echo $data['id'];?>, 'mouseout', function() {
infowindow.close();
});
<?php endforeach; ?>
The issue I'm having is that the popup info window does not display the first time. If I hover over it a second time, it works perfectly. How do I make it so it shows up the first time?

Because of asynchronous $.ajax call infoWindow content is not available at the time of the first mouseover event. You have to move definition of event handler into success: part of code.

Related

Select2 Load Remote Data Not working When URL Changed to Google Address Autocomplete AII

I have this Select2 working with its supplied example when loading
Github users data: https://api.github.com/search/repositories
but NOT working anymore when replace the AJAX url call to
Google Address Autocomplete:
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Vict&types=geocode&language=fr&key=*************************
my codes:
<select class="js-data-example-ajax">
<option value="3620194" selected="selected">select2/select2</option>
</select>
<script>
function formatRepo (repo) {
if (repo.loading) return repo.text;
var markup = '<div class="clearfix">' +
'<div class="col-sm-1">' +
'<img src="' + repo.owner.avatar_url + '" style="max-width: 100%" />' +
'</div>' +
'<div clas="col-sm-10">' +
'<div class="clearfix">' +
'<div class="col-sm-6">' + repo.full_name + '</div>' +
'<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' +
'<div class="col-sm-2"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' +
'</div>';
if (repo.description) {
markup += '<div>' + repo.description + '</div>';
}
markup += '</div></div>';
return markup;
}
function formatRepoSelection (repo) {
//return repo.description || repo.text;
return repo.full_name || repo.text;
}
$(document).ready(function(){
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
});
</script>
the error showing is :
XMLHttpRequest cannot load https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Vict&types=geocode&language=fr&key=**************************&q=v. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.
Can someone who has integrated Google Map Api and Select2 help? I am not too sure where to troubleshoot from here now...
***I am building my app in Laravel 5
***I already tried installing barryvdh/laravel-cors, but same problem!!
Try to add $.ajaxSetup with csrf token:
before ajax call:
$.ajaxSetup({
headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')}
});
and in your head meta:
<meta name="_token" content="{{ csrf_token() }}"/>
Your problem come from a security control on the HTTP protocol called 'CORS' who prevent you from making a ajax call to another domain than the one your currently on.
To fix CORS issue you must implement a specific HEADER on the server. Since Google are not owned by you it a impossibility.
So to fix this issue you can use Google Api Service and make the API do the ajax call for you. Thats mean in Select2 you will need to use not ajax{url} but ajax{transport}.
Im not sure of that part but i suppose that the Google API will create himself a frame to is service site and from that same frame do all ajax request so CORS will not be a problem.
this is a working example:
https://jsfiddle.net/sebastienhawkins/b1ws2h07/
$(document).ready(function(){
$('.placecomplete').placecomplete({
placeServiceResult:function(data,status){
console.log(data);
$('#show_something').html(data.adr_address);
},
language:'fr'
});
});
//jquery.placecomplete.js file content
//! jquery.placecomplete.js
//! version : 0.0.1
//! authors : Sébastien Hawkins
//! license : Apache
(function($){
if(typeof $.fn.select2 == 'undefined'){
console.log("ERROR: Placecomplete need Select2 plugin.")
}
//Google services
var ac = null; //Autocomplete
var ps = null; //Place
//Google config
// https://developers.google.com/maps/documentation/javascript/reference#AutocompletionRequest
var googleAutocompleteOptions = {
types: ["geocode"]
};
//Google init
window.initGoogleMapsAPI = function(){
ac = new google.maps.places.AutocompleteService();
ps = new google.maps.places.PlacesService($('<div/>')[0]); //Google need a mandatory element to pass html result , we do not need this.
}
//Google Loading
if (window.google && google.maps && google.maps.places) {
window.initGoogleMapsAPI();
} else {
$.ajax({
url: "https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false&callback=initGoogleMapsAPI",
dataType: "script",
cache: true
});
}
//Google placeservice result map
var placeServiceResult = function(data,status){
var CIVIC = 0, STREET = 1, CITY = 2, SECTEUR = 3, STATE = 4, COUNTRY = 5, ZIPCODE = 6;
//todo If the result does not have 7 element data map is not the same
//maybe we will need that html element google put mandatory
var adrc = data.address_components;
if(adrc.length != 7) return;
$('.address input.address').val(adrc[CIVIC].long_name +' '+ adrc[STREET].long_name);
$('.address input.city').val(adrc[CITY].long_name);
$('.address input.state').val(adrc[STATE].long_name);
$('.address input.country').val(adrc[COUNTRY].long_name);
$('.address input.zipcode').val(adrc[ZIPCODE].long_name);
}
//Select2 default options
var select2DefaultOptions = {
closeOnSelect: true,
debug: false,
dropdownAutoWidth: false,
//escapeMarkup: Utils.escapeMarkup,
language: 'en',
minimumInputLength: 2,
maximumInputLength: 0,
maximumSelectionLength: 0,
minimumResultsForSearch: 0,
selectOnClose: false,
theme: 'default',
width: 'resolve',
placeholder: {
id: '-1', // the value of the option
text: 'Search for address'
},
ajax:{
delay:100
}
};
//jQuery Plugin
var pluginDefault = {
placeServiceResult:placeServiceResult
}
$.fn.placecomplete = function (options) {
this.each(function () {
//Variable by instance
var $s2 = $(this);
//Init select2 for $this
$s2.select2($.extend(true,{
ajax: {
transport: function (params, success, failure) {
// is caching enabled?
//TODO(sébastien) ajouter le cache pour google autocomplete
if ($s2.data('ajax--cache')) {
}
else {
ac.getPlacePredictions($.extend(googleAutocompleteOptions,params.data),success);
}
},
data: function (params) {
return {input: params.term };
},
processResults: function (data, status) {
var response = {results:[]}
$.each(data,function(index,item){
item.text = item.description;
response.results.push(item)
});
return response;
}
}
}, select2DefaultOptions, options || {} ));
options = $.extend(true,pluginDefault,options);
$s2.on('select2:select', function (evt) {
ps.getDetails({ placeId: evt.params.data.place_id}, options.placeServiceResult);
});
});
return this;
};
})(jQuery);

update MySQL table does not work with jquery

SOLVED
I have duplicated element ID on the page.
My update table does not work. I have dialog form that selects the data from jqGrid row,
and this is the code.
function editDialog() {
//cek baris terpilih
var selr = jQuery('#list1').jqGrid('getGridParam','selrow');
if(!selr){
alert("Harap pilih baris yang ingin di edit")
return}
var namapelanggan = jQuery('#list1').jqGrid('getCell', selr, 'namapelanggan');
var alamatpelanggan = jQuery('#list1').jqGrid('getCell', selr, 'alamat');
var telppelanggan = jQuery('#list1').jqGrid('getCell', selr, 'telepon');
$("input#namapelanggan").val(namapelanggan);
$("input#alamatpelanggan").val(alamatpelanggan);
$("input#telppelanggan").val(telppelanggan);
$( "#editDialog" ).dialog("open");
}
and below is the jquery code
$(document).ready(function () {
$dialog = $("#editDialog")
.dialog({
autoOpen: false,
position: 'center',
hide: 'explode',
modal: true,
width: 'auto',
height: 'auto',
closeOnEscape: true,
buttons: [{ text: "Simpan", click: function (){
var
xnama = $("input#namapelanggan").val();
xalamat = $("input#alamatpelanggan").val();
xtelp = $("input#telppelanggan").val();
$.ajax({
type: "POST",
url: "/sis/modul/mod_pelanggan/upelanggan.php",
data: {"nama":xnama,
"alamat":xalamat,
"telp":xtelp,
success: function(result){
jQuery("#list1").trigger("reloadGrid");
},
error: function(xhr, ajaxOptions, thrownError){
alert('Terjadi kesalahan, Error Kode: ' + xhr.status);}
}
);
$( this ).dialog( "close" );
}},
{ text: "Batal", click: function () { $(this).dialog("close"); } }]
});
});
here is the upelanggan.php for query update the table.
<?PHP
include "../../../config/koneksi.php";
if ($_SERVER['REQUEST_METHOD'] == 'POST') { //halaman ini harus dipanggil melalui post
$nama = $_POST["nama"];
$alamat = $_POST["alamat"];
$telp = $_POST["telp"];
$sql="UPDATE tpelanggan SET namapelanggan='".$nama."' ,alamat='".$alamat."',telepon='".$telp."' WHERE idpelanggan=1 ";
$q = mysql_query($sql);
}
?>
User clicks edit from selected row then the dialog form is opened. User changes the input value id namapelanggan and clicks the button 'Simpan' to save changed. But it doesn't work, the table not updated.
In first check that POST request is running.
You can make it by FireBug on tab "Console" or "Net"
Also you can check it by access log on your web server.
Also in your code I found errors in $.ajax run:
Strange "nopolisi":xnopolisi because varaible xnopolisi not defined.
Not exists closed brackes } for data field.
Check Javascript console for errors and fix it.

JQuery UI catcomplete not returning selected result

I am using JQuery UI remote autocomplete with Categories.
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var self = this,
currentCategory = "";
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
cat = currentCategory;
self._renderItem( ul, item );
});
}
});
$(function() {
$( "#birds" ).catcomplete({
delay:0,
source: "/search.html?term="+ $("#birds").val(),
minLength: 2,
select: function( event, ui ){
alert(ui.item.value);
}
});
});
The following is the result I get from the source:
[{"value":"Just a Product","id":"1","category":"Category Name"}]
The problem is that I can't get the alert(ui.item.value) to work and display the selected item.
Any help please?
Thanks.
This is not how you deal with the source.
see this.. http://api.jqueryui.com/autocomplete/#option-source
you can use
array
string
callback function
if you want to receive data from a page in json format, use jquery's $.ajax()
see this for ajax http://api.jquery.com/jQuery.ajax/
you can do something like
$.ajax({url: 'search.php?term='+$("#birds").val(),
dataType: 'json',
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Accept","application/json");
},
async: false,
success: function(data){
bArray=new Array;
bJson=data;
bArray.push(bJson[0].value);
bArray.push(bJson[0].id);
bArray.push(bJson[0].category);// for multiple records put these 3 lines in loop and replace 0 with a counter
}
});
$( "#birds" ).autocomplete({
source: bArray,
select:function(event,ui)
{alert(ui.item.value);}
});
dont forget to declare bArray, bJson
BUT i would still say you are doing it wrong. Instead of using value,id,category together you use use only one of them as autocomplete. can you tell what are you exactly showing in autocomplete

JqueryMobile Cache Ajax issue

I have a strange issue with my jquery mobile application. Below screen shot from Chrome Developer Tools Snapshot.
Why does my Pages or Scripts are cached even thiugh Have added
$.ajaxSetup ({
cache: false
});
Also in every ajax call which loads my ul > li have set cache:false.
Kindly let me know how can I overcome this scenario coz of this my Mobile cache is growing on every single click driving me nuts.
Thanks
Update :
Every time I click to navigate to another page this scripts get executed :
$('body').on('click', '.menuClass', function(e) {
e.preventDefault();
e.stopImmediatePropagation();
var menuid = $(this).attr('id');
if (menuid == '100001') {
settings.get('setval', function(obj) {
if(obj.value.tableMode == "1"){
$.mobile.changePage('categories.html', {
transition : "slide"
});
return false;
}
else{
$.mobile.changePage('index.html', {
transition : "slide"
});
}
});
}
});
But for somereasons the URL for categories.html loads on every click changing the url to
below
http://localhost:8080/categories?_=1347279588477
http://localhost:8080/categories?_=1347279584203
http://localhost:8080/categories?_=1347279688227
I don't know why cache:false doesn't work but i'm adding a time created string to prevent caching of ajax pages.
Doing this by adding &ts="+ new Date().getTime() to end of url .
Here is my usage ;
$.ajax({
type: "GET",
url: "ajax.php?ajax_file=ajax_table_page&ts="+ new Date().getTime(),
success: function(data){
..................
}
});
I also use this to trace ajax errors (you may add after document is ready )
$.ajaxSetup({
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});

Can't fadeOut div element with AJAX

I can't understand why I can't fade out div element. I'm trying to delete mysql entry, delete function working fine when I reload a page entry dissapears, but I need that entry dissapear without page refresh. tried to creat new empty div and fade out it after entry deletion, worked fine.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a[id^='delete']").click(function() {
var numrow = $(this).attr("id");
numrow = numrow.substr(6);
var eil = 'id=' + numrow;
$.ajax({
type: 'POST',
url: 'trinti.php',
data: eil,
success: function() {
numrowas = "#d"+numrow;
$(numrowas).fadeOut();
}
});
});
});
</script>
<?php
require_once('db.php');
if (isset($_GET['list'])) {
$query = "SELECT * FROM zinutes";
mysql_query("SET NAMES 'UTF8'");
$uzklausa=mysql_query($query);
$i = 1;
while($lauk = mysql_fetch_array($uzklausa)){
$r = $lauk['id'];
echo '<div id="d$r">'.$i++.'. Name: '.$lauk['name'].' Message: '.$lauk['message'].' Delete</div>';
}
}
?>
try to do the fading from complete: block.
$.ajax({
type: 'POST',
url: 'trinti.php',
data: eil,
success: function() {
}
complete: function() {
numrowas = "#d"+numrow;
$(numrowas).fadeOut();
}
});