Kendo UI/Mobile - Get JSONP and append to listview - kendo-ui

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

Related

Kendo Tooltip is empty

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

How to use Angular service in place of Ajax url property

Here is code:
loader:function(param,success,error){
$.ajax({
//url: 'http://localhost/mvcController?assetid=1&dataformat=attribute',
url: assetsMVCService.execute("mvcController", { assetId: 1, dataFormat: 'attribute' }),
dataType: 'text',
type: 'post',
success: function (data) {
alert('ok');
},
error: function () {
error.apply(this, arguments);
}
});
assetsMVCService is my wrapper for Angular service. Unfortunately, a product that I am implementing forces me to use AJAX call to get data. Normally, I would use services to get data and then scope for data binding. Is it possible to use a service assigned to the url property in the code above? Interesting enough, I am hitting server with the code above. But something gets wrong on the server.
Thanks
Yes. You could do something like this:
app.service('MVC', function($http) {
var root = 'http://localhost/mvcController';
var queryParams = '?assetid=1&dataformat=attribute';
this.get = function(num) {
return $http.get(root + '/' + num + queryParams);
};
// or if you want to pass the query params in
this.execute = function(assetId, dataFormat) {
return $http.get(root + '?assetId=' + assetId + '&dataFormat=' + dataFormat;
};
// other routes
});
Note that $http can and should be used instead of $.ajax when you're using Angular. It does pretty much the same thing as $.ajax, except it plays nice with Angular.

Modify Get Request of a Kendo UI treeview

I'm currently having trouble with my Kendo UI treeview, which essentially displays the same node each time I click it to go deeper into the tree.
My problem is that my regular get request looks like this:
something/GetChildren/3432fdsf8989/Apr222014083453AM
when I click to get the next node the request looks like this:
something/GetChildren/3432fdsf8989/Apr222014083453AM?Identifier=2323eded7664
and I want to have it like this:
something/GetChildren/2323eded7664/Apr222014083453AM
Is it possible to change the URL with a Kendo UI HierarchicalDataSource? My web service is currently Ignoring the Identifier and still using the initial ID.
function initTreeView(date, targetid) {
var requestUrl = "something/GetChildren/"+ targetid + "/" + date;
var dataSource = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url : requestUrl,
dataType : "json"
}
},
schema: {
model: {
id: "Identifier",
hasChildren: true, //all items may have Children
}
}
});
$("#treeview").kendoTreeView({
dataSource: dataSource,
dataTextField: "Message"
});
}
The url in the transport definition can be a function. Define it as a function that generates it in the proper / desired format.
transport: {
read: {
url: function(options) {
return something/GetChildren/"+ targetid + "/" + date;
}
}
}

Kendo Datasource Transport custom function not getting called

Im experiencing a rather annoying bug (?) in Kendo UI Datasource.
My Update method on my transport is not getting called when I pass a custom function, but it does work if I just give it the URL.
This works:
...
transport: {
update: { url: "/My/Action" }
}
...
This does not
...
transport: {
update: function(options) {
var params = JSON.stringify({
pageId: pageId,
pageItem: options.data
});
alert("Update");
$.ajax({
url: "/My/Action",
data:params,
success:function(result) {
options.success($.isArray(result) ? result : [result]);
}
});
}
}
...
The function is not getting invoked, but an ajax request is made to the current page URL, and the model data is being posted, which is rather odd. Sounds like a bug to me.
The only reason I have a need for this, is because Kendo can't figure out that my update action returns only a single element, and not an array - so, since I dont want to bend my API just to satisfy Kendo, I though I'd do it the other way around.
Have anyone experienced this, and can point me in the right direction?
I also tried using the schema.parse, but that didn't get invoked when the Update method was being called.
I use myDs.sync() to sync my datasource.
Works as expected with the demo from the documentation:
var dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax( {
url: "http://demos.kendoui.com/service/products",
dataType: "jsonp",
success: function(result) {
options.success(result);
}
});
},
update: function(options) {
alert(1);
// make JSONP request to http://demos.kendoui.com/service/products/update
$.ajax( {
url: "http://demos.kendoui.com/service/products/update",
dataType: "jsonp", // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
// send the updated data items as the "models" service parameter encoded in JSON
data: {
models: kendo.stringify(options.data.models)
},
success: function(result) {
// notify the data source that the request succeeded
options.success(result);
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
schema: {
model: { id: "ProductID" }
}
});
dataSource.fetch(function() {
var product = dataSource.at(0);
product.set("UnitPrice", product.UnitPrice + 1);
dataSource.sync();
});
Here is a live demo: http://jsbin.com/omomes/1/edit

Google Maps: openInfoWindowTabsHtml + GDownloadUrl (Ajax call) question

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

Resources