kendoMobileListView - Dynamic databinding with jSon - json

http://demos.telerik.com/kendo-ui/mobile/listview/pull-with-endless.html refering this demo we are creating kenolistview for our mobile application.
we are getting data form webapi in jSon, whend we try to bind data with list view it's giving errors we tried three methods but all are not working, please find code bellow and error bellow code.
<body>
<div data-role="view" data-init="mobileListViewPullWithEndless" data-title="Pull to refresh">
<header data-role="header">
<div data-role="navbar">
<span data-role="view-title"></span>
<a data-align="left" data-icon="add" data-role="button" data-rel="modalview" href="#modalview-add"></a>
<a data-align="right" data-role="button" class="nav-button" href="#/">Index</a>
</div>
</header>
<ul id="pull-with-endless-listview">
</ul>
</div>
<div data-role="modalview" id="modalview-add" style="width: 95%; height: 12em;">
<div data-role="header">
<div data-role="navbar">
<span>Add Product</span> <a data-click="closeModalViewAdd" data-role="button" data-align="right">
Cancel</a>
</div>
</div>
<ul data-role="listview" data-style="inset">
<li>
<label for="username">
Product Category:</label>
<input type="text" id="name" /></li>
</ul>
<a data-click="addNew" class="addNew" type="button" data-role="button">Add New Product</a>
</div>
<script type="text/x-kendo-tmpl" id="pull-with-endless-template">
<div class="product-item">
<h3>#:CatName#</h3>
</div>
</script>
<script>
function mobileListViewPullWithEndless(e) {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "http://mydomain.com/api/homescreenapp/36/8c177908-be9f-4474-b036-43e8cef736b5/345/800/web",
dataType: 'JSON'
}
},
serverPaging: true,
pageSize: 2
});
$("#pull-with-endless-listview").kendoMobileListView({
dataSource: dataSource,
template: $("#pull-with-endless-template").text(),
pullToRefresh: true,
endlessScroll: true
});
$("#addNew").click(function () {
loader.show();
addProductDataSource.add({
ProductName: $("#name").val(),
UnitPrice: Math.floor((Math.random() * 10) + 1)
});
});
}
function closeModalViewAdd() {
$("#modalview-add").kendoMobileModalView("close");
}
function addNew() {
addProductDataSource.add({
ProductName: $("#name").val(),
UnitPrice: Math.floor((Math.random() * 10) + 1)
});
closeModalViewAdd();
}
var addProductDataSource = new kendo.data.DataSource({
transport: {
create: {
url: " http://mydomain.com/api/homescreenapp/36/8c177908-be9f-4474-b036-43e8cef736b5/345/800/web",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { type: "string" }
}
}
},
autoSync: true,
batch: true,
requestEnd: function () {
$("#name").val("");
}
});
</script>
<script>
window.kendoMobileApplication = new kendo.mobile.Application(document.body);
</script>
</body>
We are getting following jSon response from our webapi
{"Categories":[{"CategoryId":"305","CatName":"Clothing","Description":"","ParentId":"0","ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Category/ResizeImage/345webMan&woman.jpg","MapUrlRewrite":"Clothing"},{"CategoryId":"306","CatName":"Shoes","Description":"","ParentId":"0","ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Category/ResizeImage/345web2.jpg","MapUrlRewrite":"Shoes"},{"CategoryId":"307","CatName":"Handbags","Description":"","ParentId":"0","ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Category/ResizeImage/345web3.jpg","MapUrlRewrite":"Handbags"},{"CategoryId":"308","CatName":"Accesories","Description":"","ParentId":"0","ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Category/ResizeImage/345web4.jpg","MapUrlRewrite":"Accesories"},{"CategoryId":"309","CatName":"Luggage","Description":"","ParentId":"0","ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Category/ResizeImage/345web5.jpg","MapUrlRewrite":"Luggage"},{"CategoryId":"310","CatName":"Jewellery","Description":"","ParentId":"0","ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Category/ResizeImage/345web6.jpg","MapUrlRewrite":"Jwellery"},{"CategoryId":"344","CatName":"Eye Wear","Description":"","ParentId":"0","ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Category/ResizeImage/345web7.jpg","MapUrlRewrite":"Eye-Wear"},{"CategoryId":"345","CatName":"Watches","Description":"","ParentId":"0","ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Category/ResizeImage/345web8.jpg","MapUrlRewrite":"Top-Brands"},{"CategoryId":"346","CatName":"Hot Brands","Description":"","ParentId":"0","ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Category/ResizeImage/345webHot_Brands.jpg","MapUrlRewrite":"Hot-Deals--Offers"}],"HomeBannerImages":[{"ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Banners/ResizeImage/800webBanner_1.jpg","BannerTitle":"Banner Clothing","BannerDescription":"","CategoryId":null},{"ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Banners/ResizeImage/800webshoes-banner_2.jpg","BannerTitle":" shoes banner","BannerDescription":"","CategoryId":null},{"ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Banners/ResizeImage/800webhandbag-banner1.jpg","BannerTitle":"handbag ","BannerDescription":"","CategoryId":null},{"ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Banners/ResizeImage/800webLuggage_2.jpg","BannerTitle":"Laggege","BannerDescription":"","CategoryId":null},{"ImageName":"http://mydomailn.com/customerassets/company36/UploadImages/Banners/ResizeImage/800webjewelry_2.jpg","BannerTitle":"jewelry","BannerDescription":"","CategoryId":null}],"CustomerLogo":"http://mydomailn.com/iconnect/Images/eapparelCustomerLogo12.png"}
Code and Error :
With above code if we bind kendoMobileListView we are getting error "Uncaught SyntaxError: Unexpected token"
if we use dataType: “json” instead of dataType: “jsonp”, I am getting error like "Uncaught TypeError: Cannot call method 'slice' of undefined"
If we use dataType: “json” instead of dataType: “json array”, it is not displaying anything in listing and even in error. It mean all things will be blank.
We have gone through with all below parameter. But still not getting any success.
dataType: 'JSONP',
jsonpCallback: 'jsonCallback',
type: 'GET',
async: false,
crossDomain: true
Please guide me on this issue, I need to bind only Category name in the list.
FYI : i cann't change webapi response as it's being used by other services of client.
Thanks,
Ashish

Kendo expects the server to return a JSON array. In your case it returns an object with a Categories property where the data array is stored. You need to tell the Kendo DataSource to pull the data from .Categories using the schema.data configuration option.
... = new DataSource({
...
schema: {
data: "Categories"
}
});

Related

Send data to another javascript library with vue

With vue, I create a json file with classic asp from Sql Server and import the data. My goal is to place the data I have received on the page and in apexCharts.
The html page I used, getData.js and json from dataSql.asp is as follows.
index.html
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="vue.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<style> textarea { position: fixed; right: 0; top: 0; width: 300px; height: 400px; } </style>
</head>
<body>
<div id="app">
<form id="urlParameterForm">
<input type="date" name="startDate" id="startDate" />
<input type="date" name="endDate" id="endDate" />
<input
type="number"
name="pageNumber"
id="pageNumber"
value="1"
v-on:input="changePage"
/>
<input
type="button"
value="Filter"
id="Filter"
v-on:click="changeFilter"
/>
<p>Page : {{ pageActive }}</p>
</form>
<h3>{{title}}</h3>
<div v-for="dta in dataTable.sqlData">
Height: {{dta.height}}, Type: {{dta.type}}
<ul v-for="dta in dataTable.sqlData.graphData">
<li>{{dta.categorie}} - {{dta.serie}}</li>
</ul>
</div>
<textarea>
{{dataTable}}
</textarea>
</div>
<script src="getData.js"></script>
</body>
</html>
getData.js
const app = new Vue({
el: "#app",
devtools: true,
data: {
dataTable: [],
pageNumber: 1,
pageActive :0,
title:'Graph-1'
},
computed: {
url() {
return './dataSql.asp?pg=' + this.pageNumber
}
},
methods: {
changePage: function (event) {
console.log('Change Page',this.pageNumber);
this.pageNumber = event.target.value;
this.init();
},
changeFilter: function (event) {
console.log('Change Filter');
this.init();
},
init() {
let that = this;
console.log('init call');
$.ajax({
type: "POST",
url: that.url,
data:{
startDate:$('#startDate').val(),
endDate:$('#endDate').val(),
pageNumber:$('#pageNumber').val()
},
success: function (data) {
console.log('data remote call');
console.log(data.sqlData);
that.dataTable = data.sqlData;
}
});
}
},
mounted() {
this.init()
}
})
dataSql.asp response json
[
{
"height": 350,
"type": "bar",
"graphData": [
{
"categorie": "Bursa",
"serie": 4
},
{
"categorie": "Tekirdağ",
"serie": 3
}
]
}
]
When I run the page, the screen calls the data like this and I see the data coming as json.
Under the graph-1 text, the does not show anything as if I have never written this. But I can print json text in the text field as it appears in the upper right corner.
<div v-for="dta in dataTable.sqlData">
Height: {{dta.height}}, Type: {{dta.type}}
<ul v-for="dta in dataTable.sqlData.graphData">
<li>{{dta.categorie}} - {{dta.serie}}</li>
</ul>
</div>
<textarea>
{{dataTable}}
</textarea>
I actually want to assign this data, which I could not show on the page, to x and y variables here.
I need something like the following.
categories: app.dataTable.graphData.categorie;
series: app.dataTable.graphData.serie;
var barBasicChart = {
chart: {
height: 350,
type: 'bar',
},
plotOptions: {
bar: {
horizontal: true,
}
},
dataLabels: {
enabled: false
},
series: [{
data: [4,3] /* vue - json - graphData.serie */
}],
xaxis: {
categories: ['Bursa','Tekirdağ'], /* vue - json - graphData.categories */
},
fill: {
colors: $themeColor
}
}
// Initializing Bar Basic Chart
var bar_basic_chart = new ApexCharts(
document.querySelector("#denemeGrafik"),
barBasicChart
);
bar_basic_chart.render();
Vue seems to have not been developed for a long time. I'm new to vuede too. My goal is to automatically generate html content from json. To change the variables of the scripts I have used (such as apexcharts, xGrid etc.).
Can you suggest if there is another javascript library that I can do these things with?
Except for React and Angular because these two are hard to understand and write.
Your AJAX callback assigns dataTable to data.sqlData:
$.ajax({
//...
success: function (data) {
that.dataTable = data.sqlData;
}
})
Then, your component tries to render dataTable.sqlData, but sqlData was already extracted in the AJAX callback (dataTable is an Array):
<div v-for="dta in dataTable.sqlData">
^^^^^^^ ❌
Solution: You can either update the AJAX callback to return the full response (including sqlData):
$.ajax({
//...
success: function (data) {
that.dataTable = data;
}
})
...or update the template to not dereference sqlData, using dataTable directly:
<div v-for="dta in dataTable">

React output JSON from API

I have managed to get JSON from my api I have created, however I am having trouble actually rendering that JSON. I have managed to output it in the console by 'stringify'-ing it, however I cannot seem to actually render JSON to the page.
import React, { Component } from 'react';
import './App.css';
import $ from 'jquery';
function getData() {
return $.ajax({
type: "GET",
url: 'http://localhost:3001/data',
data: {},
xhrFields: {
withCredentials: false
},
crossDomain: true,
dataType: 'json',
success: handleData
});
}
function handleData(data /* , textStatus, jqXHR */ ) {
console.log(JSON.stringify(data));
return JSON.stringify(data);
}
class App extends Component {
render() {
return (
<div className="App">
<header>
<h2>Last Application Deployment </h2>
</header>
<div id='renderhere'>
{JSON.stringify(getData().done(handleData))}
</div>
</div>
);
}
}
export default App;
you cant execute a function in render method in return.you can use react lifecycles and store result in state like this =>
class App extends Component {
state = {result : null}
componentDidMount = ()=>{
$.ajax({
type: "GET",
url: 'http://localhost:3001/data',
data: {},
xhrFields: {
withCredentials: false
},
crossDomain: true,
dataType: 'json',
success: (result)=>{
this.setState({result : result});
}
});
};
render() {
return (
<div className="App">
<header>
<h2>Last Application Deployment </h2>
</header>
<div id='renderhere'>
{this.state.result && and what you want because i dont know why you want use JSON.stringfy - you use .map() or ...}
</div>
</div>
);
}
}
I suggest you see this article and this.
I've made a demo of how you can solve this: http://codepen.io/PiotrBerebecki/pen/amLxAw. The AJAX request should not be made in the render method but in a componentDidMount() lifecycle method. Also, it's best to store the response in state. Please see the guidance in the React docs: https://facebook.github.io/react/tips/initial-ajax.html
Fetch data in componentDidMount. When the response arrives, store the data in state, triggering a render to update your UI.
Here is the full code:
class App extends React.Component {
constructor() {
super();
this.state = {
time: '',
string: ''
};
}
componentDidMount() {
$.ajax({
type: "GET",
url: 'http://date.jsontest.com/'
})
.then(response => {
this.setState({
time: response.time,
string: JSON.stringify(response)
});
})
}
render() {
return (
<div className="App">
<header>
<h2>Last Application Deployment </h2>
</header>
<div id='renderhere'>
Time: {this.state.time} <br /><br />
String: {this.state.string}
</div>
</div>
);
}
}
ReactDOM.render(
<App />, document.getElementById('content')
);

Microsoft Azure with AngularJS - Data not being displayed in chart

I am able to view data locally, however when I open the Windows Azure cloud service application, there is no longer Json data being passed into my chart (http://dashboardexample.cloudapp.net/Home/Product). I get a message in the Console saying "Controller names should start with an uppercase character and end with the suffix Controller. For example: UserController.
The best practice for module names is to use lowerCamelCase. Check the name of "dx"." Not sure what is causing this issue. Any thoughts?
AngularJS
var app = angular.module('customCharts', ['dx']);
app.controller("ChartController", function ($scope, $http, $q) {
$scope.productSettings = {
dataSource: new DevExpress.data.DataSource({
load: function () {
var def = $.Deferred();
$http({
method: 'GET',
url: 'http://localhost:53640/Home/PostChart'
}).success(function (data) {
def.resolve(data);
});
return def.promise();
}
}),
series: {
title: 'Displays Product Costs for items in our Database',
argumentType: String,
argumentField: "Name",
valueField: "Cost",
type: "bar",
color: '#008B8B'
},
commonAxisSettings: {
visible: true,
color: 'black',
width: 2
},
argumentAxis: {
title: 'Items in Product Store Database'
},
valueAxis: {
title: 'Dollor Amount'
}
}
})
HTML
<script type="text/javascript" src="~/Scripts/angular.js"></script>
<script type="text/javascript" src="~/Scripts/angular-sanitize.js"></script>
<script type="text/javascript" src="~/Scripts/globalize/globalize.js"></script>
<script type="text/javascript" src="~/Scripts/dx.chartjs.js"></script>
#Scripts.Render("~/Scripts/ChartDesign.js")
<div ng-app="customCharts">
<div ng-controller="ChartController">
<div dx-chart="productSettings"></div>
</div>
</div>
As GauravMantri mentioned, you need to reference the name and location of your controller function. Ex: I had to reference /Home/PostChart in my dataSource url. this solved the issue.
AngularJS
var app = angular.module('customCharts', ['dx']);
app.controller("ChartController", function ($scope, $http, $q) {
$scope.productSettings = {
dataSource: new DevExpress.data.DataSource({
load: function () {
var def = $.Deferred();
$http({
method: 'GET',
url: '/Home/PostChart'
}).success(function (data) {
def.resolve(data);
});
return def.promise();
}
}),
series: {
title: 'Displays Product Costs for items in our Database',
argumentType: String,
argumentField: "Name",
valueField: "Cost",
type: "bar",
color: '#008B8B'
},
commonAxisSettings: {
visible: true,
color: 'black',
width: 2
},
argumentAxis: {
title: 'Items in Product Store Database'
},
valueAxis: {
title: 'Dollor Amount'
}
}
})

json data not showing properly

i used flexigrid and the data that are supposed to be displayed in it are displayed instead in a white page, image here:
here is my view:
#using (Html.BeginForm("JsonEmployee", "Employees", FormMethod.Post))
{
#Html.ValidationSummary(true)
<fieldset>
<h5>
ENTER A NAME TO FILTER THE LIST:</h5>
<div style="float: left">
<input name="nameSelected" type="text" /> &nbsp </div>
<div style="float: left">
<input class="btn btn-inverse" type="submit" value="FILTER" /></div>
</fieldset>
}
<table class="flex" style="display: none">
</table>
<script type="text/javascript" language="javascript">
$('.flex').flexigrid({
url: '/Employees/JsonEmployee',
dataType: 'json',
method: 'GET',
colModel: [
{ display: 'NUMBER', name: 'number', width: 200, sortable: true, align: 'center' },
{ display: 'NAME', name: 'name', width: 300, sortable: true, align: 'center' },
{ display: 'ROLE', name: 'role', width: 200, sortable: true, align: 'center'}],
searchitems: [
{ display: 'NUMBER', name: 'number' },
{ display: 'NAME', name: 'name', isdefault: true }
],
sortname: "number",
sortorder: "name",
usepager: true,
title: 'Employees',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 950
});
</script>
and here is my controller:
[Authorize(Users = "Admin")]
[HttpPost]
public ActionResult JsonEmployee(String nameSelected)
{
CacheClear();
var employees = db.Employees.Where(r => r.Name.Contains(nameSelected)).OrderBy(r => r.Name);
var res = new
{
page = 1,
total = employees.Count(),
rows = employees.Select(x => new { x.Number, x.Name, x.Role })
.ToList()
.Select(x => new
{
id = x.Number,
cell = new string[]
{
x.Number,
x.Name,
x.Role
}
}).ToArray(),
};
return Json(res, JsonRequestBehavior.AllowGet);
}
i have a form which accepts a string input from users.. if the user clicks the submit button, the flexigrid in my page should be populated by a filtered list.. however, the page redirects to a white page with the data of json just like the picture above...
You have created an HTML form pointing to the /Employees/JsonEmployee action. So when you submit this form it is normal that the browser will send a POST request to this controller action and redirect to it and show the results of its execution. That's how HTML works. If you want to stay on the same page you could AJAXify this form and cancel the default action. Like this:
$('form').submit(function () {
// Send an AJAX request to the controller action that this HTML <form>
// is pointing to in order to fetch the results in a JSON form
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
// When the AJAX request succeeds we get the result returned
// by the controller action which represents the JSON data source
// for the flexgrid. So all that's left is rebind the grid with
// this new data source:
$('.flex').flexAddData(result);
}
});
// Prevent the browser from redirecting to the /Employees/JsonEmployee action
return false;
});

qtip plugin doesn't work with jquery jtemplates plugin

I'm using Ajax to load data.
With help of jQuery jTemplates I load data within Container. I need to apply jqtip plugin to images withing Container, but for some reason it's not working. if it outside works fine.
Any idea why it's not working? maybe give me an idea how I can debug it?
Here is my code
$.ajax({
type: "POST",
url: "/json/default.aspx/loaditems",
data: "{'parameter':'" + parameter + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
ApplyTemplate(msg);
}
});
function ApplyTemplate(msg) {
$('#Container').setTemplateURL('/scripts/template.htm', null, { filter_data: true });
$('#Container').processTemplate(msg);
}
<div id="Container">
</div>
here is content of my template.htm page
{#foreach $T.d as post}
<div class="image_wrap" style="float: left;">
<a href="{$T.post.url}">
<img width="175" src="{$T.post.profimage}" title="test" /></a>
</div>
{#/for}
here is qtip code
<script type="text/javascript">
$(function () {
$('.image_wrap img[title]').qtip({
position: {
corner: {
target: 'topMiddle',
tooltip: 'bottomMiddle'
}
},
style: {
name: 'cream',
padding: '7px 13px',
color: '#350608',
width: {
max: 250,
min: 0
},
tip: true
}
});
});
</script>
You're running your qtip logic on $(document).ready(). The problem is that because you're loading new markup after the page has loaded, the qtip logic doesn't apply to it.
Try wrapping your qtip logic inside a function, then call the function after you run your AJAX call.
Something like this:
function InitQtip() {
$('.image_wrap img[title]').qtip({
position: {
corner: {
target: 'topMiddle',
tooltip: 'bottomMiddle'
}
},
style: {
name: 'cream',
padding: '7px 13px',
color: '#350608',
width: {
max: 250,
min: 0
},
tip: true
}
});
}
// This will take care of items loaded with the page.
$(function () {
InitQtip();
}
// This will take care of new items.
$.ajax({
type: "POST",
url: "/json/default.aspx/loaditems",
data: "{'parameter':'" + parameter + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
ApplyTemplate(msg);
InitQtip();
}
});