I am facing the following problem.
On an Google Map I want to add info windows with tabs, where content is loaded from an external file using the GDownloadUrl method.
The code works about fine, but with two problems.
a) The first time I click on a marker, nothing hapens. I need to click twice to get an info box. After that it works ok.
b) When I close an info box and open it again, the tabs repeat themselves. Every time I reopen the info box, those tabs get repeated. So, if using the code below and open the info box 3 times, I get 6 tabs (Info, Photos, Info, Photos, Info, Photos). Any idea of what I am doing wrong here?
I have also tried this with JQuery's $.get method, but the results are exactly the same.
function createREMarker(lat,long,reID)
{
var reMarker = new GMarker(rePoint,iconRE);
GEvent.addListener(reMarker, "click", function()
{
GDownloadUrl('testcontent.php?reID='+reID+'&what=info', function(data) {
content1 = data;
});
GDownloadUrl('testcontent.php?reID='+reID+'&what=photos', function(data) {
content2 = data;
});
tabs.push(new GInfoWindowTab('Info', '<div id="mapOverlayContent" style="width:375px; height:220px; overflow:auto;">'+content1+'</div>'));
tabs.push(new GInfoWindowTab('Photos', '<div id="mapOverlayContent" style="width:375px; height:220px; overflow:auto;">'+content2+'</div>'));
reMarker.openInfoWindowTabsHtml(tabs);
});
return reMarker;
};
Firstly you are using v2 of the API which is now officially deprecated. For a site I maintain I do the following (this is v3 of the API and uses jQuery):
function createMarker(point, id, markerOptions) {
var marker = new google.maps.Marker(point,markerOptions);
var Lat = point.lat();
var Lng = point.lng();
google.maps.Event.addListener(marker, "click", function() {
$.ajax({
type: "GET",
url: "/data/specific.xml?id=" + id,
dataType: "xml",
success: function(xml) {
var this_marker = $(xml).find('marker');
var name = $(this_marker).attr("name");
details_tab = details_tab + "ID: " + id + "<br />Name: " + name + "<br />";
var infowindow = new google.maps.InfoWindow({
content: details_tab,
});
infowindow.open(map, marker);
}
});
}
return marker;
}
From what I can see tabs are no longer supported in v3 of the API? :( But this example uses tabs from jQuery UI:
http://gmaps-samples-v3.googlecode.com/svn-history/r78/trunk/infowindow/tabs.html
http://code.google.com/p/gmaps-samples-v3/source/browse/trunk/infowindow/tabs.html?r=78
Related
dI use a kendo tooltip on cells of a column of a kendo grid but the content of the tooltip is empty.
When I use the chrome debugger, values are correctly set but there is nothing in my tooltip.
$("#gri").kendoTooltip({
filter: "span.tooltip",
position: "right",
content: function (e) {
var tooltipHtml;
$.ajax({
url: ".." + appBaseUrl + "api/Infobulle?id=" + $(e.target[0]).attr("id"),
contentType: "application/json",
dataType: "json",
data: {},
type: "GET",
async: false
}).done(function (data) { // data.Result is a JSON object from the server with details for the row
if (!data.HasErrors) {
var result = data.Data;
tooltipHtml = "Identifiant : " + result.identifiant;
} else {
tooltipHtml = "Une erreur est survenue";
}
// set tooltip content here (done callback of the ajax req)
e.sender.content.html(tooltipHtml);
});
}
Any idea ? Why it is empty ?
After looking at the dev's answer on telerik forums, i found out that you need to do something like
content: function(){
var result = "";
$.ajax({url: "https://jsonplaceholder.typicode.com/todos/1", async:false , success: function(response){
result = response.title
}});
return result;
}
changing directly with e.sender.content.html() won't work, instead we have to return the value. And i tried several approach :
i tried mimick ajax call with setTimeOut, returning string inside it or using e.sender.content.html() wont work
i tried to use content.url ( the only minus i still don't know how to modify the response, i display the whole response)
the third one i tried to use the dev's answer from here
AND check my example in dojo for working example, hover over the third try
I'm facing an issue with ajax that several users here also encountered but the proposed solution do not seem to work for my case.
in my index.php file, I have:
<pre>
<script>
function ButtonManager()
{
$( "button" ).click(function()
{
var context = $(this).attr('type');
var page_type = $(this).attr('page');
var referrer = $(this).attr('referrer');
var form_type = $(this).attr('form');
var object_id = $(this).attr('object');
var postData = 'page_type='+page_type+'&form_type='+form_type+'&referrer='+referrer+'&id='+object_id;
$( '#indicator' ).css( "display", "block" );
if (context == 'post_form')
{
var formData = $('#submit_content').serialize();
postData = postData+'&context=post_form&'+formData;
}
if ((context == 'load_form') || (context == 'filter_form'))
{
postData = postData +'&context=load_form';
if (context == 'filter_form')
{
var filter1 = $('select[name=filter1]').val();
var filter2 = $('select[name=filter2]').val();
var filter3 = $('select[name=filter3]').val();
postData = postData + '&filter1='+filter1+'&filter2='+filter2+'&filter3='+filter3;
}
}
$.ajax
({
type: 'POST',
url: 'php/sl.php',
data: postData,
cache: false,
async: false,
dataType: 'html',
success: function(result)
{
ManageLayer(form_type+'_content');
$('#'+form_type+'_content').html(result);
$( '#indicator' ).css( "display", "none" );
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.responseText);
$( '#indicator' ).css( "display", "none" );
},
});
});
}
</script>
<button type="load_form" page="home" referrer="navigation" form="edit" object="">test</button>
</pre>
when a click on the test button, the script calls sl.php to retrieve some html with other buttons in it.
in the output I get from the server I have added:
<pre>
<script>
var myvar=ButtonManager();
</script>
<button type="post_form" page="home" referrer="navigation" form="edit" object="">test2</button>
</pre>
The goal of the ButtonManager function is to manage all my buttons in one function so it needs to be available/known everywhere (in index.php where it's loaded and in all the output I can get from sl.php).
I have added the var myvar=ButtonManager() line because it's the only way I have found to make sure the function is known by the server output. The drawback is that the function is executed multiple times instead of one even if I don't click on the test2 button.
So I'm looking either for a way to prevent my function from being executed multiple times or an alternative to make the function available everywhere.
I don't know what approach would be the best, I'm a casual developper programming for fun and javascript / ajax is not the language I know the best.
Thanks
Laurent
I got the answer from another forum but I wanted to share it in case others are having the same problem.
Code to be used should be like this:
<pre>
$( document ).on("click", "button", function() {
</pre>
It makes the function available to objects that do not exist yet.
I have a page that has a few divs connected in a flowchart via JS-Graph.It. When you click one of the divs, I want it to 1) generate text in a special div 2) generate a popup via click functions attached to the two classes "block" and "channel" in each div. This works when the page is static.
When I add ajax so on click of a button and add more divs, only one of the two classes appears in the HTML source. "Channel" is no longer visible and the function to generate a pop-up on click of a channel class div does not work anymore...
AJAX call:
$("#trace").bind('click', $.proxy(function(event) {
var button2 = $('#combo').val();
if(button2 == 'default') {
var trans = 'Default View';
}
if(button2 == 'abc') {
var trans = 'abc';
}
$.ajax({ // ajax call starts
url: 'serverside.php', // JQuery loads serverside.php
data: 'button2=' + $('#combo').val(), // Send value of the clicked button
dataType: 'json', // Choosing a JSON datatype
success: function(data) // Variable data constains the data we get from serverside
{
JSGraphIt.delCanvas('mainCanvas');
$('.test').html('<h1>' + trans + '</h1>'); // Clear #content div
$('#mainCanvas').html(''); // Clear #content div
$('#mainCanvas').append(data);
JSGraphIt.initPageObjects();
}
});
return false; // keeps the page from not refreshing
}, this));
DIV class: (works in index.php but not transactions.php)
// Boxes
while($row = sqlsrv_fetch_array($result))
{
echo '<div id="'.$row['id'].'_block" class="block channel" style="background:';
Functions:
$(document).on('click', '.block', $.proxy(function(event) {
var input = $(event.target).attr('id');
var lines = input.split('_');
var button = lines[0];
$.ajax({
url: 'srv.php',
data: 'button=' + button,
dataType: 'json',
success: function(data)
{
$('#content').html('');
$('#content').append(data);
}
});
return false;
}, this)); // End Application Details
$(".channel").click(function () {
alert('channel');
});
Something about registering with pages, I'm not sure exactly how it works. The fix should be to change your channel click function to be the same as your first and use the .on('click') option.
found some related reading material. https://learn.jquery.com/events/event-delegation/
I'm just starting out with Kendo mobile (impressed so far - coming from JQM). I'm trying to pass a postcode to a url which returns some json (houses near that area) and then append it to a listview using Datasource. However, it fails an in console I just get:
Error [object Object]
Heres my code: ** Updated **
var app = new kendo.mobile.Application(document.body,
{
transition:'slide'
});
function onBodyLoad() {
//document.addEventListener("deviceready", onDeviceReady, false);
// Use the following for testing in the browser
getProperties(onResult);
}
function getProperties(callback) {
var template = kendo.template($("#propertiesListViewTemplate").html());
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: 'http://www.someurl.me/getproperties.php?postcode=hx59ay',
dataType: "jsonp"
}
},
schema: {
data: "listing" //??? Not sure what this should be???
},
error: function(e) {
console.log("Error " + e);
},
change: function() {
$("#propertyResultListView").html(kendo.render(template, this.view()));
console.log(this.view());
}
});
dataSource.read();
$("#propertyResultListView").kendoMobileListView({dataSource:dataSource,template: $("#propertiesListViewTemplate").html()});
}
function onResult(resultData) {
console.log("Results " + listing);
$("#propertyResultListView").kendoMobileListView({dataSource: kendo.data.DataSource.create({data:resultData}),
template: $("#propertiesListViewTemplate").html()});
}
I'm sure this is down to the schema part of the Datasource but I'm lost as to what it should be (the docs havent really helped).
The JSON thats returned is:
{"country":"England","result_count":510,"longitude":-1.826866,"area_name":"Caldercroft, Elland HX5","listing":[{"image_caption":"Main Image","status":"for_sale","num_floors":"0","listing_status":"sale","num_bedrooms":"2","agent_name":"Daniel & Hirst","latitude":53.688934,"agent_address":"110 Commercial Street","num_recepts":"0","property_type":"Detached","country":"England","longitude":-1.843375,"first_published_date":"2012-10-11 19:05:42","displayable_address":"Elland HX5","street_name":"EXLEY LANE","num_bathrooms":"0","thumbnail_url":"http://images.zoopla.co.uk/f7f6791d95dadef11b340be2949bd8957079168f_80_60.jpg","description":"Comments","post_town":"Elland","details_url":"http://www.zoopla.co.uk/for-sale/details/26491359","agent_logo":"http://static.zoopla.co.uk/zoopla_static_agent_logo_(120721).png","price_change":[{"date":"2012-10-11 16:45:02","price":"37500"}],"short_description":"We are pleased to offer ...","agent_phone":"01484 954009","outcode":"HX5","image_url":"http://images.zoopla.co.uk/f7f6791d95dadef11b340be2949bd8957079168f_354_255.jpg","last_published_date":"2012-11-21 17:31:46","county":"West Yorkshire","price":"37500","listing_id":"26491359"}
Could someone point me in the right direction? The whole datasource schema is confusing to me. If it helps to describe what I'm trying to do in JQM I'd do something like
$.getJSON(serviceURL + 'getproperties.php?postcode=' + postcode + '&minimum_beds=' + minimumBeds + '&minimum_price=' + minimumPrice + '&maximum_price=' + maximumPrice , function(data) {
$('#propertyList li').remove();
// Loop through json data and append to table
listings = data.listing;
$.each(listings, function(index, property) {
console.log(property.image_url);
console.log(property.price);
$('#propertyList').append('<li><a href="propertydetails.html?id=' + property.listing_id + '">' +
'<img src="' + property.thumbnail_url + '"/>' +
'<h6>' + property.property_type + '</h6>' +
'<p>' + property.displayable_address + '</p>' +
'<p><strong>£' + property.price + '</strong></p>');
$('#propertyList').listview('refresh');
});
});
Template
<!-- Template for Property results, need to change below fields -->
<script type="text/x-kendo-template" id="propertiesListViewTemplate">
<h4>${property_type}</h4>
<p>${street_name}</p>
</script>
* Update - Code updated for Pechka answer **
I have now changed my service to return jsonp (with a callback) as per the link you mentioned. I can now see the jsonp in developer tool network tab -
jQuery17106739131917711347_1354193012656({"country":"England","result_count":179,"longitude":-1.83261282209016,"area_name":"Elland","listing":[{"image_caption":"","rental_prices":{"per_week":75,"accurate":"per_month","per_month":"325"},"status":"to_rent","num_floors":"0","listing_status":"rent","num_bedrooms":"1","agent_name":"Boococks","latitude":53.68668 ...
Nothing is getting populated into my template though, so no list view is created (I realize this is probably down to my newness to kendo). Can you see where I'm going wrong, this seems incredably tricky compared to JQM... Thanks again for your help.
Ok I'm just trying to simplify this thing to see where the error happens.
So you define your DataSource with a parameterMap and a Model:
var dataModel = new kendo.data.Model.define({
id: 'listing_id' //specifies a unique key, every other key is mapped automatically
});
var dataSource = new kendo.data.DataSource({
transport: {
parameterMap:function (_data, _operation) {
if (_operation == 'read') {
return {
postcode: 'bd11db' //sending parameters via parameterMap
};
}
},
read: {
url: 'http://www.someurl.me/getproperties.php',
dataType: "jsonp"
}
},
schema: {
//data: "ResultSet.Result" //data specifies which "node" to use for the actually returned data, since you want the complete object you dont need to specify this
model: dataModel //using the specified model
},
error: function(e) {
console.log("Error " + e);
},
change: function() {
$("#propertyResultListView").html(kendo.render(template, this.view()));
console.log(this.view());
}
});
dataSource.read();
Sorry I dont really see through all these callbacks at first glance, but this datasource should at least return (or log) the JSON you get from the serverMight not solve your problem completely, but may be a hint in the right direction ;) Feel free to comment on things that are unclear or (hopefully not) wrong Good Luck :)
I suggest you to configure your service to return jsonp (jsonwithpadding).
You can see the dataSource bound to a jsonp in action in this demo. Use the network tab of the browsers developer tools and see the difference in the format.
Try this:
Wrap your jsonp reply in a var like "results" so that it looks like this:
jQuery1820051476528169587255_1366217103715({"results":[{"id":"3","entry_stamp":"November 30, -0001 12:00 am","comments":null}]})
Designate the wrapper var:
schema: {
data: "results" //the portion of your jsonp that you want
}
Call the template:
$("#propertyResultListView").kendoMobileListView({
dataSource:dataSource,
template: $("#propertiesListViewTemplate").html()});
You shouldnt need to call dataSource.read(); as the call to the template will do this autoMagically. Try this below as a completed code view (i removed some other items that may cause issues - you will need to replace them once you get this simple version working:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: 'http://www.someurl.me/getproperties.php?postcode=hx59ay',
dataType: "jsonp"
}
},
schema: {
data: "results" //your reply data
}
});
$("#propertyResultListView").kendoMobileListView({
dataSource:dataSource,
template: $("#propertiesListViewTemplate").html()
});
there were a few question similar to mine on the stack but none that answered my question, so...
An ajax call returns the standard html code for creating the like button:
<div class="fb-like" data-href="http://www.website.com" data-send="true" data-width="450" data-show-faces="true"></div>
This html does show up in the source when looked at with 'inspect element', but it is not rendered, i.e. the space where the button should be is blank. Is there some rendering function that I should be using?
Any hints would be greatly appreciated!
EDIT: Here's the ajax request and parseing - the 'like' button is put in '#thequestion' along with some other text (it is echoed from question.php).
$("#thequestion").load("/thought/question.php", { ans: choice, id: questionId } );
$("#graph").load("/thought/graph.php", { id: questionId } );
$("#fbCommentsPlaceholder").html("<div class='fb-comments' data-href='http://qanai.com/thought/#" + questionId + "' data-num-posts='2' data-width='470'></div>");
FB.XFBML.parse();
eval(document.getElementById('thequestion').innerHTML);
eval(document.getElementById('graph').innerHTML);
(I know eval is evil)
EDIT 2: The like button appears if FB.XFBML.parse(); is executed manually (in the console) after the ajax call.
Thanks
You have to call FB.XFBML.parse(); after the ajax call.
Documentation: https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse/
Edit: now I see that you're trying to load content into $('#thequestion'). .load takes a callback that runs after the request completes. You should do something like:
$('#thequestion').load('/my/url', { my: 'params' }, function() {
FB.XFBML.parse();
});
Documentation: http://api.jquery.com/load/
Not sure anyone needs it, but my complete code looks like this now and renders both FB page and Like button appropriatelly (LikeLink button created with material icon):
<i id="LikeLink" class="material-icons actionButton"></i>
var fbloaded = false; // if SDK is loaded, no need to do it again (though cache should do this?
var fbpageid = "myPageId"; // FB page id
// ajax call to FB SDK script
if (!fbloaded) {
$.ajax({
type: "GET",
url: "//connect.facebook.net/en_US/sdk.js",
dataType: "script",
cache: true,
success: function () {
fbloaded = true;
FB.init({
appId: '{myAppId}',
version: 'v2.3' // or v2.0, v2.1, v2.0
});
// parse button after success
FB.XFBML.parse();
}
});
}
var FBDivAppended = false; // if already done, do not call and render again
PostUrl = window.location.href; // like button needs this... or not :)
// when LikeLink is clicked, add the divs needed and at the end fire the FB script ajax call (resetFB)
$("#LikeLink").click(function () {
if (!FBDivAppended) {
var $pagediv = $("<div class=\"fb-page\" data-href=\"https://www.facebook.com/" + fbpageid + "\" />");
var $fblikediv = $("<div class=\"fb-like\" data-href=\"" + PostUrl + "\" />");
var $fbdiv = $("<div id=\"fbDiv\" />");
var $fbroot = $("<div id=\"fb-root\" />");
$fbdiv.append($pagediv).append($fblikediv);
$(".Header").append($fbdiv).append($fbroot);
FBDivAppended = true;
}
resetFB();
}