How to use Kendo UI MVC Extensions with require js? - asp.net-mvc

I have a controller that looks like this:
using System.Collections.Generic;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
namespace KendoMvcApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetData([DataSourceRequest] DataSourceRequest req)
{
var products = CreateProducts();
var result = products.ToDataSourceResult(req);
return Json(result);
}
private static IEnumerable<Product> CreateProducts()
{
for (int i = 1; i <= 20; i++)
{
yield return new Product
{
ProductId = i,
ProductName = "Product " + i,
ProductPrice = i * 2.5
};
}
}
}
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public double ProductPrice { get; set; }
}
}
And a view that looks like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="~/Content/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendo.default.min.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/require.js"></script>
</head>
<body>
<div id="grid"></div>
<script type="text/javascript">
require.config({
baseUrl : '#Url.Content("~/Scripts")',
paths: {
'jquery': 'jquery-2.0.3.min',
'kendo': 'kendo-ui'
},
shim: {
'jquery': {
exports: 'jQuery'
}
}
});
require(['jquery', 'kendo/kendo.grid.min'], function ($) {
$(document).ready(function () {
$('#grid').kendoGrid({
dataSource: {
schema: {
data: 'Data',
total: 'Total',
aggregates: 'AggregateResults',
model: {
id: "ProductId",
fields: {
ProductName: { type: "string" },
ProductPrice: { type: "number" }
}
}
},
transport: {
read: {
url: "#Url.Action("GetData", "Home")",
dataType: "json",
method: "post"
}
},
pageSize: 10,
serverPaging: true,
serverSorting: true,
type: "aspnetmvc-ajax"
},
sortable: {
mode: "single"
},
columns: ["ProductName", "ProductPrice"],
scrollable: false,
pageable: true
});
});
});
</script>
</body>
</html>
And my directory structure is:
Scripts/kendo-ui/* (all the kendo files, including the mvc one)
Scripts/require.js
Scripts/jquery-2.0.3.min.js
which nearly works except that server-side sorting doesn't get applied.
This is because the kendo.aspnet.mvc.min.js file is never downloaded (of course, as require JS doesn't know anything about it) so to remedy that I tried this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="~/Content/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendo.default.min.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/require.js"></script>
</head>
<body>
<div id="grid"></div>
<script type="text/javascript">
require.config({
baseUrl: '#Url.Content("~/Scripts")',
paths: {
'jquery': 'jquery-2.0.3.min',
'kendo': 'kendo-ui',
'kendo-mvc': 'kendo/kendo.aspnetmvc.min'
},
shim: {
'jquery': {
exports: 'jQuery'
}
}
});
require(['jquery', 'kendo-mvc', 'kendo/kendo.grid.min'], function ($) {
$(document).ready(function () {
$('#grid').kendoGrid({
dataSource: {
schema: {
data: 'Data',
total: 'Total',
aggregates: 'AggregateResults',
model: {
id: "ProductId",
fields: {
ProductName: { type: "string" },
ProductPrice: { type: "number" }
}
}
},
transport: {
read: {
url: "#Url.Action("GetData", "Home")",
dataType: "json",
method: "post"
}
},
pageSize: 10,
serverPaging: true,
serverSorting: true,
type: "aspnetmvc-ajax"
},
sortable: {
mode: "single"
},
columns: ["ProductName", "ProductPrice"],
scrollable: false,
pageable: true
});
});
});
</script>
</body>
</html>
But that produced this error:
And attempted to load the js files thus:
The red spots are 404 not found as it is looking for the js files in a folder called kendo under the scripts folder.
So then I thought I would try including the all version instead so I tried this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="~/Content/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendo.default.min.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/require.js"></script>
</head>
<body>
<div id="grid"></div>
<script type="text/javascript">
require.config({
baseUrl: '#Url.Content("~/Scripts")',
paths: {
'jquery': 'jquery-2.0.3.min',
'kendo': 'kendo-ui/kendo.all.min',
'kendo-mvc': 'kendo-ui/kendo.aspnetmvc.min'
},
shim: {
'jquery': {
exports: 'jQuery'
}
}
});
require(['jquery', 'kendo', 'kendo-mvc'], function ($) {
$(document).ready(function () {
$('#grid').kendoGrid({
dataSource: {
schema: {
data: 'Data',
total: 'Total',
aggregates: 'AggregateResults',
model: {
id: "ProductId",
fields: {
ProductName: { type: "string" },
ProductPrice: { type: "number" }
}
}
},
transport: {
read: {
url: "#Url.Action("GetData", "Home")",
dataType: "json",
method: "post"
}
},
pageSize: 10,
serverPaging: true,
serverSorting: true,
type: "aspnetmvc-ajax"
},
sortable: {
mode: "single"
},
columns: ["ProductName", "ProductPrice"],
scrollable: false,
pageable: true
});
});
});
</script>
</body>
</html>
But that produced these errors:
And attempted to load the js files thus:
In this case - the red spots are 404 not found as it is looking for the files directly under the Scripts folder.
So here is my question:
How can I include said file in a require JS type scenario?
Aside: I would like to be using the kendo.all.min file and not the separate ones as I want to use knockout-kendo in the future and that seems to not work with the separate file but if the only way to make this work is to use the separate file approach, that is fine.

It took me a while to get your code working but after having been fiddling around with it a little I managed to get the sorting to work with just a tiny little change in your original code.
The only thing I changes was on the require line where I added the mvc file as well. Then all the paths became correct and it all worked out fine.
['jquery', 'kendo/kendo.grid.min', 'kendo/kendo.aspnetmvc.min']
In my code I've used "Kendo UI for ASP.NET MVC Q2 2013" with the jQuery.min.js file that was included in that package. The complete View code then becomes:
<script type="text/javascript">
require.config({
baseUrl : '#Url.Content("~/Scripts")',
paths: {
'jquery': 'jquery-2.0.3.min',
'kendo': 'kendo-ui'
},
shim: {
'jquery': {
exports: 'jQuery'
}
}
});
require(['jquery', 'kendo/kendo.grid.min', 'kendo/kendo.aspnetmvc.min'], function ($) {
$(document).ready(function () {
$('#grid').kendoGrid({
dataSource: {
schema: {
data: 'Data',
total: 'Total',
aggregates: 'AggregateResults',
model: {
id: "ProductId",
fields: {
ProductName: { type: "string" },
ProductPrice: { type: "number" }
}
}
},
transport: {
read: {
url: "#Url.Action("GetData", "Home")",
dataType: "json",
method: "post"
}
},
pageSize: 10,
serverPaging: true,
serverSorting: true,
type: "aspnetmvc-ajax"
},
sortable: {
mode: "single"
},
columns: ["ProductName", "ProductPrice"],
scrollable: false,
pageable: true
});
});
});
</script>
I hope it'll work in your code as well.

Let's try building up from a minimal working version. You said you have the following in the directory:
Scripts/kendo-ui/* (all the kendo files, including the mvc one)
Scripts/require.js
Scripts/jquery-2.0.3.min.js
To get that to load all the dependencies, you might try something like this:
<html>
<body>
<script type="text/javascript" src="~/Scripts/require.js"></script>
<script type="text/javascript">
require.config({
baseUrl: '#Url.Content("~/Scripts")',
paths: {
'jquery': 'jquery-2.0.3.min',
'kendo': 'kendo-ui/kendo.all.min',
'kendo-mvc': 'kendo-ui/kendo.aspnetmvc.min'
},
shim: {
'jquery': {
exports: 'jQuery'
},
'kendo-mvc' : {
deps: ['kendo'] //kendo needs to be loaded before kendo-mvc?
}
}
});
require(['jquery', 'kendo', 'kendo-mvc'], function ($) {
});
</script>
</body>
</html>
I played around with putting it in a jsFiddle, but ran into a number of problems (Kendo actually requires jQuery 1.9.0, etc.) that you can probably resolve on your own.
The key seems to be that your last version is loading kendo.data, kendo.combobox, and a bunch of other files that aren't referenced anywhere. Figuring out where those requests came from would help solve this mystery.
Update:
Here's one possibility. If kendo-mvc is loading dependencies like this:
["./kendo.data.min","./kendo.combobox.min","./kendo.multiselect.min","./kendo.‌​validator.min"]
Then it may fail because RequireJS looks for dependencies relative to the name of the module, which has been aliased as kendo-mvc. Let's try not renaming it (see below), and see if that works:
<script type="text/javascript">
require.config({
baseUrl: '#Url.Content("~/Scripts")',
paths: {
'jquery': 'jquery-2.0.3.min',
'kendo-ui/kendo': 'kendo-ui/kendo.all.min',
'kendo-ui/kendo-mvc': 'kendo-ui/kendo.aspnetmvc.min'
},
...
require(['jquery', 'kendo-ui/kendo', 'kendo-ui/kendo-mvc'], function ($) {
});

Related

Graph in popup and separate Div in Leaflet

I wonder if anyone can tell me what is wrong in my code please? I want to be able to select a polygon and show a graph in a popup using leaflet and highchart. I have managed to create the graph in the popup, but the line is missing on it, and I also get a separate div showing the same chart (and the line) at the bottom of my web page which I don't want. Can anyone tell me how to get the line to show on the chart in the popup and to remove the separate chart? Here is my code.enter code here
<!DOCTYPE html>
<html>
<head>
<title>Quick Start - Leaflet</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--include leaflet CSS file-->
<link rel="stylesheet" href="css/leaflet.css" />
<link rel="markers" type="images/marker-icon" href="images/marker-icon.png" />
<!--include Leaflet Javascript file-->
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="js/leaflet.js"></script>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script src='http://unpkg.com/leaflet#1.0.2/dist/leaflet.js'></script>
<script src="js/esri-leaflet.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
</head>
<body>
<!--Put a div element with a certain id where you want your map to be: -->
<div id="map" style="width: 1000px; height: 800px;"></div>
<div id="chartcontainer" class="highchart" style="width: 500px; height: 200px;"></div>
<!-- First we’ll initialize the map and set its view to our chosen geographical coordinates and a zoom level:-->
<script>
var mymap = L.map('map', {
zoomControl:true, maxZoom:28, minZoom:1
}).fitBounds([[51.0269253989,-1.34762355597],[51.1990603009,-0.951310026203]]);
L.esri.basemapLayer('Imagery').addTo(mymap);
//loads geoserver layer as WMS
var field_boundaries = L.tileLayer.wms("http://localhost:1997/geoserver/RSAC/wms", {
layers: 'RSAC:results_clipped_with_growth_small_new',
format: 'image/png',
transparent: true,
version: '1.1.0',
attribution: "myattribution"
});
//loads the geojson layer
var owsrootUrl = 'http://localhost:1997/geoserver/RSAC/wms';
var defaultParameters = {
service : 'WFS',
version : '2.0',
request : 'GetFeature',
typeName : 'RSAC:results_clipped_with_growth_small_new',
outputFormat : 'json',
format_options : 'callback:getJson',
SrsName : 'EPSG:4326'
};
var parameters = L.Util.extend(defaultParameters);
var URL = owsrootUrl + L.Util.getParamString(parameters);
var ajax = $.ajax({
url : URL,
dataType : 'json',
jsonpCallback : 'getJson',
success : function (response) {
L.geoJson(response, {
onEachFeature: function (feature, url) {
url.on('click', function(e){
var chartplotoptions ={
chart: {
type: 'line'
},
title: {
text: 'Growth'
},
xAxis: {
allowDecimals: true,
categories: ['20151114', '20151126', '20151208', '20151220', '20160113', '20160125', '20160206', '20160218', '20160301', '20160313', '20160325', '20160406', '20160418', '20160430', '20160512', '20160524', '20160605', '20160629', '20160723', '20160804', '20160816'],
labels: {
formatter: function () {
return this.value;
}
}
},
yAxis: {
startOnTick: false,
minPadding: 0.05,
title: {
text: 'Crop Growth',
},
labels: {
formatter: function () {
return this.value;
}
}
},
tooltip: {
pointFormat: '{series.name}{point.y}'
},
plotOptions: {
area: {
pointStart: -20,
threshold: 10,
marker: {
enabled: false,
symbol: 'circle',
radius: 2,
states: {
hover: {
enabled: false
}
}
}
}
},
series: [{
name: 'Growth',
data: [parseFloat(feature.properties.Date_20151114),parseFloat(feature.properties.Date_20151126),parseFloat(feature.properties.Date_20151208), parseFloat(feature.properties.Date_20151220), parseFloat(feature.properties.Date_20160113), parseFloat(feature.properties.Date_20150125), parseFloat(feature.properties.Date_20160206), parseFloat(feature.properties.Date_20160218), parseFloat(feature.properties.Date_20160301), parseFloat(feature.properties.Date_20160313), parseFloat(feature.properties.Date_20160325), parseFloat(feature.properties.Date_20160406), parseFloat(feature.properties.Date_20160418), parseFloat(feature.properties.Date_20160430), parseFloat(feature.properties.Date_20160512), parseFloat(feature.properties.Date_20160524), parseFloat(feature.properties.Date_20160605), parseFloat(feature.properties.Date_20160629), parseFloat(feature.properties.Date_20160723), parseFloat(feature.properties.Date_20160804), parseFloat(feature.properties.Date_20160816)]
},
]
};
$('#chartcontainer').highcharts(chartplotoptions);
url.bindPopup($('#chartcontainer').html());
url.openPopup();
});
}
}).addTo(mymap);
}
});
</script>
</body>
</html>
You don't need the div element in your HTML markup. You can create one on the fly in your onEachFeature function and add it to the popup. Also, you need to initialize your highchart after the popup has opened, not before. In code with comments:
new L.GeoJSON(feature, {
onEachFeature: function (feature, layer) {
// Create div with class name highchart
var div = L.DomUtil.create('div', 'highchart');
// Bind popup to layer with div as content
layer.bindPopup(div);
// Handle event when popup opens
layer.on('popupopen', function (e) {
console.log(e.target); // layer object
console.log(e.target.feature); // layer's feature object
console.log(e.popup); // popup object
console.log(e.popup.getContent()); // the div
// Now do the highcharts stuff
Highcharts.chart(e.popup.getContent(), { /**/ });
});
}
});
And don't forget to set the div's dimensions with CSS:
.highchart {
width: 500px;
height: 200px;
}

Redirect before selecting an item Select2

I'm using Select2 v4.0.3 and I populate the element using ajax.
$("#el").select2({
multiple: true
maximumSelectionSize: 1,
ajax: {
url: url,
data: function (params) {
return {
name: params.term
};
},
processResults: function (data) {
return {
results: $.map(data.results, function(obj) {
return {id: obj.id, text: obj.name, key: obj.key};
}
})
};
}
}
});
I want to redirect the client before a result is selected. The problem is I need the key attribute from the clicked result. To understand better what I want to do, I paste here a snippet that works after the selection is made.
$("#el").on("select2:select", function(e) {
var selected = $(this).select2('data')[0];
location.href = base_url + '?key=' + selected.key;
});
You can use event.params.args.data.id to get the key attribute from the clicked result. So, your code would probably work like:
$("#el").on("select2:select", function(e) {
var selected = event.params.args.data.id;
location.href = base_url + '?key=' + selected;
});
I slightly modified the official Github repositories example to show my point.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<select class="js-data-example-ajax" style="width: 100%">
<option value="3620194" selected="selected">select2/select2</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
$(".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, params) {
// 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, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: $.map(data.items, function(ghrepo) {
return {
text: ghrepo.archive_url,
id: ghrepo.archive_url
}
})
}
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
},
minimumInputLength: 1
}).on('select2:selecting', function(event, params) {
event.preventDefault();
repoId = event.params.args.data.id;
console.log(repoId);
});
</script>
</body>
</html>

Ext.Ajax.request not working

![
this is the project structure I am using. On adding a local URL like this below code is not working. url:'data/showStudentInfo.html']3I am using Ext Js version 4.1.1
In my application , I am having a grid, which uses a store.
On clicking "click me" button I want to redirect to the server, for test purpose I am using a basic google url,
But the class Ext.Ajax.Request is not working I think
Please help , as I am new to Ext js, I am not aware of the mistake I am making.
I am trying this in notepad++, as well as in eclipse ide (indigo version).
both with same output, Ext.Ajax.Request part not working.
It will of great help if anyone have suggestion as if I want to send
Thanking in advance
Below is my html and js file
practiseCellEditEx.js
Ext.require([
'Ext.data.*',
'Ext.Ajax.',
'Ext.grid.*'
]);
function getRandomDate() {
var from = new Date(1900, 0, 1).getTime();
var to = new Date().getTime();
var date = new Date(from + Math.random() * (to - from));
return Ext.Date.clearTime(date);
}
function createFakeData(count) {
var firstNames = ['Ed', 'Tommy', 'Aaron', 'Abe'];
var lastNames = ['Spencer', 'Maintz', 'Conran', 'Elias'];
var data = [];
for (var i = 0; i < count ; i++) {
var dob = getRandomDate();
var firstNameId = Math.floor(Math.random() * firstNames.length);
var lastNameId = Math.floor(Math.random() * lastNames.length);
var name = Ext.String.format("{0} {1}", firstNames[firstNameId], lastNames[lastNameId]);
data.push([name, dob]);
}
return data;
}
Ext.onReady(function(){
Ext.define('Person',{
extend: 'Ext.data.Model',
fields: ['Name', 'dob']
});
var store = Ext.create('Ext.data.Store', {
model: 'Person',
autoLoad: true,
proxy: {
type: 'memory',
data: createFakeData(10),
reader: {type: 'array'}
},
sorters: [{
direction:'ASC'
}]
});
Ext.create('Ext.grid.Panel', {
store: store,
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit : 1
})
],
columns: [
{
text: "Name",
width:120,
dataIndex: 'Name',
editor : {
xtype: 'textfield',
allowBlank:false
}
},
{
text: "DOB",
width: 120,
dataIndex: 'dob',
renderer: Ext.util.Format.dateRenderer('M d, Y'),
editor: {
xtype: 'datefield',
format: 'M d, Y',
minValue: '01/01/1900',
maxValue: new Date()
}
},
{
xtype: 'actioncolumn',
width: 30,
sortable: false,
menuDisabled: true,
items: [{
icon: 'http://etf-prod-projects-1415177589.us-east-1.elb.amazonaws.com/trac/docasu/export/2/trunk/client/extjs/shared/icons/fam/delete.gif',
handler: function(grid, rowIndex, colIndex) {
store.removeAt(rowIndex);
}
}]
}
],
renderTo:'example-grid',
width: 280,
height: 280
});
Ext.create('Ext.Button', {
text: 'Click me',
// renderTo: Ext.getBody(),
renderTo:'myBtn',
handler: getName
});
function getName (btn)
{
alert("hello");
var records = store.getAt(1);
alert('the name at index 1 is:'+records.get('Name'));
Ext.Ajax.request({
url : 'https://www.google.co.in/'
});
};
/*
function buttonClicked() {
Ext.MessageBox.confirm( 'Delete this part ? :' );
}*/
});
practiseCellEditEx.html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>ExtJS Samples</title>
<link rel="stylesheet" type="text/css" href="../resources/css/ext-all.css" />
<script type="text/javascript" src="../adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../ext-all.js"></script>
<script type="text/javascript" src="practiseCellEditEx.js"></script>
</head>
<body>
<h2> <b>Helllo , today's Date is 02.12.2015 </b></h2>
<div id="example-grid"></div>
<!--<button id="myBtn"></button>-->
<div id="myBtn"></div>
</body>
</html>
The problems seems to be simply the request going to google.com. In my browser it is blocked because it is a cross-origin request (an ajax request to another domain), see also here for further information: https://en.wikipedia.org/wiki/Same-origin_policy.
The same code with a request to a local URL works fine.

how to draw charts with json file data in highcharts

my json.data file is in the same directory as my index.html file. data.json file looks like this:
{
data:
[
[1369540800000,20]
]
}
when I do:
alert(JSON.stringify(jsonData, null, 4));
I get this back, so I get the values. Still dont know what is wrong.
{
"data":[
[
1369540800000,
10
],
[
1369541700000,
20
]
]
}
my html file including java script to build the charts is below:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>HIGHTCHARTS</title>
<style>
body
{
font: 10px arial;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$.getJSON('data.json', function(jsonData) {
chartOptions.series = jsonData;
chart = new Highcharts.Chart(chartOptions);
});
var chartOptions = {
chart: {
renderTo: 'container'
},
xAxis: {
type: 'datetime'
},
series: []
};
});
</script>
</head>
<body>
<div id="container" style="width:100%; height:400px;"></div>
</body>
</html>
I see the chart title but I dont see any charts or data points. What am I missing here?
Your data is not in the right format. Familiarize yourself with how to format data for Highcharts.
These may help:
http://api.highcharts.com/highcharts#series.data
http://docs.highcharts.com/#preprocesssing-data-from-a-file
Notably:
1) your dates must be either a javascript time stamp (epoch time, in milliseconds), or a date.Utc declaration
2) your structure needs to be like:
[[date, value],[date,value],[date,value]]
this is what I had to do to make it work:
<script src="js/highcharts.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'area'
},
xAxis: {
type: 'datetime'
},
series: [{}]
};
$.getJSON('dude.json', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>

JayData / Phonegap works in iPad Simulator but not iPad device

I am doing a proof of concept app using the the following blog as code base.
http://jaydata.org/blog/how-to-check-if-your-websql-environment-is-working
When I run the following in iPad 6.1 Simulator using XCode 4.6.1, I can see the expected output.
[LOG] Received Event: deviceready
[LOG] begin testing
[LOG] define Department Entity
[LOG] define Employee Entity
[LOG] saving Entity done.
But when I run the following to an actual iPad device via USB, its output ends at "define Department Entity". I don't see any errors; here are the console.log outputs:
[LOG] Received Event: deviceready
[LOG] begin testing
[LOG] define Department Entity
Any help would be much appreciated.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
<!--jQuery-->
<script type="text/javascript" src="jquery/jquery-1.7.2.js"></script>
<script type="text/javascript" src="jquery/jquery.mobile-1.1.1.js"></script>
<!--jayData and the different providers used-->
<script type="text/javascript" src="js/JayData-1.2.7.1/JayData.js"></script>
<script type="text/javascript" src="js/JayData-1.2.7.1/jaydataproviders/SqLiteProvider.js"></script>
<!--PhoneGap-->
<script type="text/javascript" src="cordova-2.5.0.js"></script>
</head>
<body>
<div class="app">
<h1>Apache Cordova</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
</div>
</div>
<script type="text/javascript" src="cordova-2.5.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
<script type="text/javascript">
var jqmReady = $.Deferred(),
pgReady = $.Deferred();
// mobileinit does not work. pageinit works.
// jqm ready
$(document).bind("pageinit", jqmReady.resolve);
// phonegap ready
document.addEventListener("deviceready", pgReady.resolve, false);
// all ready :)
$.when(jqmReady, pgReady).then(function () {
console.log('begin testing');
console.log('define Department Entity');
$data.Entity.extend("$org.types.Department",
{
Id: { type: "int", key: true, computed: true },
Name: { type: "string", required: true },
Employees: {
type: Array,
elementType: "$org.types.Employee",
inverseProperty: "Department"
}
});
console.log('define Employee Entity');
$data.Entity.extend("$org.types.Employee",
{
Id: { type: "int", key: true, computed: true },
Name: { type: "string", required: true },
Department: { type: $org.types.Department, inverseProperty: 'Employees' }
});
$data.EntityContext.extend("$org.types.OrgContext", {
Department: { type: $data.EntitySet, elementType: $org.types.Department },
Employee: { type: $data.EntitySet, elementType: $org.types.Employee }
});
$org.context = new $org.types.OrgContext({
name: "webSql", databaseName: "OrgDatabase",
dbCreation: $data.storageProviders.DbCreationType.DropTableIfChanged
});
var department = new $org.types.Department({ Name: 'Department1' });
var employee = new $org.types.Employee({ Name: 'John Smith' });
department.Employees = [employee];
$org.context.onReady(function () {
$org.context.Department.add(department);
$org.context.saveChanges();
});
console.log('saving Entity done.');
});
</script>
</body>
</html>
answered on jaydata forum, but I copy here, maybe somebody else will search for this
important points:
1. use jquery 1.8+, 1.7 is not supported. if you must use 1.7 then please use q promise, tell us if you have any problems
2. unfortunatelly you can subscribe to deviceready event after onload event only....
this code works for us on ipad 6.1
(function main() {
var jqmReady = $.Deferred();
var pgReady = $.Deferred();
// mobileinit does not work. pageinit works.
// jqm ready
$(document).bind("pageinit", jqmReady.resolve);
// phonegap ready
$.when($.ready)
.then(function(){
document.addEventListener("deviceready", pgReady.resolve, false);
});
var Employee = $data.define('Employee', {
Id: { type: "int", key: true, computed: true },
Name: { type: "string", required: true },
Department: { type: "Department", inverseProperty: 'Employees' }
});
var Department = $data.define('Department', {
Id: { type: "int", key: true, computed: true },
Name: { type: "string", required: true },
Employees: { type: Array, elementType: "Employee", inverseProperty: 'Department' }
});
var OrgDatabase = $data.EntityContext.extend('OrgDatabase', {
Departments: { type: $data.EntitySet, elementType: Department },
Employees: { type: $data.EntitySet, elementType: Employee }
});
var context = new OrgDatabase({name: 'webSql', databaseName: 'OrgDatabase', dbCreation: $data.storageProviders.DbCreationType.DropTableIfChanged});
// all ready :)
$.when(jqmReady, pgReady, context.onReady()).then(function () {
var employee = new Employee({ Name: 'John Smith' });
var department = new Department({ Name: 'Department1' });
department.Employees = [employee];
context.Departments.add(department);
context.saveChanges(function() {
alert('saving Entity done.');
});
});
})()
I used Web Inspector and found out the app on iPad could not load "JayData.js".
It turns out the actual js file has a filename with all lowercase characters. Thus, the fix is to change "JayData.js" to "jaydata.js", and the app works on iPad.
http://developer.apple.com/library/ios/#documentation/AppleApplications/Reference/SafariWebContent/DebuggingSafarioniPhoneContent/DebuggingSafarioniPhoneContent.html

Resources