My Application is MVC 5; I return list of specific dates using ajax:
events = x.Day.Year + ", " + (x.Day.Month -1) + ", " + x.Day.Day
I get the correct dates: 2019, 11, 8 .. etc.
The example I am following is using an array of dates as follows:
var events = [+new Date(today.getFullYear(), today.getMonth(), 8)];
I tried:
success: function (result) {
if (result && result.events.length > 0) {
for (var g = 0; g < result.length; g++) {
events.push(new Date(result[g].events));
}
};
}
Did not work!
Looks like your success function is incorrectly accessing the events array within result. Try updating your success function with the snippet below:
success: function (result) {
if (result && result.events && result.events.length > 0) {
for (var g = 0; g < result.events.length; g++) {
events.push(new Date(result.events[g]));
}
};
}
Related
I tried the below custom paste function to paste only values but it doesn't trigger the change event in order for me to sync the data to the data source.
Dojo Demo Link
...
change: onExcelChange,
paste: function(e) {
e.preventDefault()
var currentRange = e.range;
var fullData = e.clipboardContent.data;
var mergedCells = e.clipboardContent.mergedCells;
var topLeft = currentRange.topLeft();
var initialRow = topLeft.row;
var initialCol = topLeft.col;
var origRef = e.clipboardContent.origRef;
var numberOfRows = origRef.bottomRight.row - origRef.topLeft.row + 1;
var numberOfCols = origRef.bottomRight.col - origRef.topLeft.col + 1;
var spread = e.sender;
var sheet = spread.activeSheet();
var rangeToPaste = sheet.range(initialRow, initialCol, numberOfRows, numberOfCols);
sheet.batch(function() {
for(var i = 0; i < fullData.length; i += 1) {
var currentFullData = fullData[i];
for(var j = 0; j < currentFullData.length; j += 1 ) {
var range = sheet.range(initialRow + i, initialCol + j);
var value = currentFullData[j].value;
if (value !== null) {
range.input(value);
range.format(null);
}
}
}
sheet.select(rangeToPaste);
}, { layout: true, recalc: true });
} ...
I have tried to use recalc: true in sheet.batch to trigger the change to no avail. Any help would be greatly appreciated.
All Kendo widgets inherit from Observable, which has a trigger method:
var obj = new kendo.Observable();
obj.bind("myevent", function(e) {
console.log(e.data); // outputs "data"
});
obj.trigger("myevent", { data: "data" });
You need to manually trigger the Spreadheet's change event with its correct parameters.
I am using the following code to sort the rows of a table based on Ids. I am using Dragula for drag and drop functionality. The Sorted Ids is presented in the variable sortedIDs. The alert present within if(sortedIDs) is showing an alert, but no request is being sent using AJAX.
var container = document.getElementById('tb');
var rows = container.children;
var nodeListForEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
var sortableTable = dragula([container]);
var pingu='';
sortableTable.on('dragend', function() {
nodeListForEach(rows, function (index, row) {
//alert(row.id);
pingu=pingu+','+row.id;
//alert(pingu);
// row.lastElementChild.textContent = index + 1;
// row.dataset.rowPosition = index + 1;
});
var sortedIDs=pingu;
pingu='';
// alert (sortedIDs);
if (sortedIDs) {
alert(sortedIDs);
$.ajax({
type: 'GET',
url: '<?php echo $site_url . 'index.php/API/p2376ghDSPOLWYBdhBT'?>',
data: 'lmqSPOEhyVt87H6tBYSfdreg=' + sortedIDs + '&hjhqweuty87685gh87GCfsc6HF=' + sbds98JWUDGHKJ98yujg,
success: function (tata) {
alert (tata);
if (tata == '1') {
$("#success").show();
$('#success').delay(2000).fadeOut('slow');
} else {
$("#failure").show();
$('#failure').delay(5000).fadeOut('slow');
}
}
});
} else {
//$('#ms').html('<option value="">Select Q level first</option>');
}
});
And when i am adding
error : function(jqXHR, textStatus, errorThrown){
}
for showing AJAX error, it starts throwing the alert too.
Any sort of help would be deeply appreciated.
Thanks
I solved the problem. I forgot to retrieve the value of an attribute and send it to the API.
var sbds98JWUDGHKJ98yujg = $('#p2JMopns3hfBubNNHJeer').val();
net MVC application, in which I have multiple charts. On these charts, I have applied filters and by clicking each filter, I do an ajax call which returns the result in Json and then applies to the charts.
Now its working perfectly in Firefox and Chrome, but in Internet Explorer - Ajax call is always unsuccessful. I tried hitting the web api url directly through my browser and the issue it seems is, the result json was being returned as a file to be downloaded.
This is my ajax code :
function getIssueResolvedGraphdata(control, departCode, departName) {
$.ajax(
{
type: "GET",
url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (myData) {
var resolvedStartDate = myData.data.IssueResolvedStartDate;
var issueData = myData.data.IssueData;
var resolveData = myData.data.ResolvedData;
//converting issueData into integer array...
var issue = issueData.replace("[", "");
var issue1 = issue.replace("]", "");
var issue2 = issue1.split(",");
for (var i = 0; i < issue2.length; i++) { issue2[i] = parseInt(issue2[i]); }
//converting resolvedData into integer array
var resolve = resolveData.replace("[", "");
var resolve1 = resolve.replace("]", "");
var resolve2 = resolve1.split(",");
for (var j = 0; j < resolve2.length; j++) { resolve2[j] = parseInt(resolve2[j]); }
//getting max value from array...
var issueMaxVal = Math.max.apply(null, issue2);
var resolveMaxVal = Math.max.apply(null, resolve2);
//Eliminating leading zeros in issue array
var removeIndex = 0;
var myDate;
var newDate;
var arrayLength;
if (issueMaxVal != 0) {
arrayLength = issue2.length;
for (var i = 0; i < arrayLength; i++) {
if (issue2[0] == 0) {
issue2.splice(0, 1);
removeIndex = i;
} else {
break;
}
}
//Getting days count of current month
var monthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
var monthEnd = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1);
var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
var monthDays = 0;
if (monthLength == 28) {
monthDays = removeIndex;
}
else if (monthLength == 30) {
monthDays = removeIndex + 1;
}
else if (monthLength == 31 || monthLength == 29) {
monthDays = removeIndex + 2;
}
//matching the resultant issue array with resolve array & setting start date
var iDate = resolvedStartDate;
var tDate = '';
for (var i = 0; i < iDate.length; i++) {
if (iDate[i] == ',') {
tDate += '/';
}
else {
tDate += iDate[i];
}
}
if (removeIndex != 0) {
resolve2.splice(0, (removeIndex + 1));
var myDate = new Date(tDate);
myDate.setDate(myDate.getDate() + monthDays);
newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
} else {
var myDate = new Date(tDate);
newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
}
} else {
alert("Empty");
}
//updating chart here...
var chart = $('#performance-cart').highcharts();
chart.series[0].update({
pointStart: newDate,
data: issue2
});
chart.series[1].update({
pointStart: newDate,
data: resolve2
});
if (issueMaxVal > resolveMaxVal) {
chart.yAxis[0].setExtremes(0, issueMaxVal);
} else {
chart.yAxis[0].setExtremes(0, resolveMaxVal);
}
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
} });}
Code from web api controller :
[HttpGet]
[CrossDomainActionFilter]
public Response<GraphIssueResolvedWrapper> GetQueryIssueResolvedData(string deptCode)
{
Response<GraphIssueResolvedWrapper> objResponse = new Response<GraphIssueResolvedWrapper>();
GraphIssueResolvedWrapper objGraphIssueResolvedWrapper = new GraphIssueResolvedWrapper();
try
{
....code.....
objResponse.isSuccess = true;
objResponse.errorDetail = string.Empty;
objResponse.data = objGraphIssueResolvedWrapper;
}
catch (Exception ex)
{
objResponse.isSuccess = false;
objResponse.errorDetail = ex.Message.ToString();
objResponse.data = null;
}
return objResponse;
}
Reponse Class :
public class Response<T>
{
public bool isSuccess { get; set; }
public string errorDetail { get; set; }
public T data { get; set; }
}
I am stuck at this for hours now. Any help will be appreciated.
I have solved my problem by using the following code : ( I guess it needed CORS support)
function isIE() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE");
if (msie > 0)
return true;
return false;
}
Then in document.ready function of my binding script :
$(document).ready(function () {
if (isIE())
$.support.cors = true;
});
Note : it still download Json stream as a file but now my AJAX call is successful upon each hit.
You've missed contentType: 'text/html' which is pretty important for IE7-8:
$.ajax(
{
type: "GET",
url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
dataType: "json",
contentType: 'text/html'
crossDomain: true,
async: true,
cache: false,
success: function (myData) {
var result = JSON.parse(myData);
///...code...
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
}
}
);
To make it works in IE7-8 you also need to be sure that you've writing Conrent-Type Header into your response on server side. Add this line right before return statement;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html; charset=iso-8859-1");
And in code probably you will need to parse result in success method by using JSON.parse(myData);
I have the next code:
$.get('Lubricantes/getListaEquipos', function (data) {
if (data.length > 0) {
var peticion = base_datos_local.transaction(['Equipos'], 'readwrite').objectStore('Equipos').clear();
total_equipos = data.length;
peticion.onerror = function () {
console.log('No se pudo limpiar el maestro de equipos.');
};
peticion.onsuccess = function (e) {
for (var i = 0; i < data.length; i++) {
var peticion = base_datos_local.transaction(['Equipos'], 'readwrite').objectStore('Equipos').add(data[i]);
peticion.onerror = function (e) {
console.log('No se pudo cargar el equipo' + i);
};
peticion.onsuccess = function (e) {
console.log('Equipo ' + i + ' agregado');
};
}
};
}
});
When this execute the var i don't exist, how can pass to add method the value of i?
Async is fun, isn't it?
I'll save you the lecture on scopes and variable references and just recommend that you just wrap the guts of your for loop into an "immediately invoked anonymous function" like so:
$.get('Lubricantes/getListaEquipos', function (data) {
if (data.length > 0) {
var peticion = base_datos_local.transaction(['Equipos'], 'readwrite').objectStore('Equipos').clear();
total_equipos = data.length;
peticion.onerror = function () {
console.log('No se pudo limpiar el maestro de equipos.');
};
peticion.onsuccess = function (e) {
for (var i = 0; i < data.length; i++) {
(function(entrada, j) {
var peticion = base_datos_local.transaction(['Equipos'], 'readwrite').objectStore('Equipos').add(entrada);
peticion.onerror = function (e) {
console.log('No se pudo cargar el equipo' + j);
};
peticion.onsuccess = function (e) {
console.log('Equipo ' + j + ' agregado');
};
})(data[i], i);
}
};
}
});
data[i] is evaluated immediately and passed in as an argument to this closure, so you'll have the correct reference in scope when the callbacks eventually fire.
I'm trying to display a pie chart in my website using Google charts API so far i cant get it to work and I couldn't find any examples that use MVC 3 Razor.
here is my code im using json to get the data
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', { 'packages': ['corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
JSON.stringify = JSON.stringify || function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof (v);
if (t == "string") v = '"' + v + '"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
$.post('#Url.Content("~/Home/GetMyChart1")',
function (items) {
// Successful requests get here
alert(JSON.stringify(items) + " - " + items.rows.length);
data.addRows(items.rows.length);
$.each(items.rows, function (i, item) {
alert(i);
data.setCell(i, 0, item.Name);
data.setCell(i, 1, item.ID);
});
alert("finished");
alert(data.length);
});
// Set chart options
var options = { 'title': 'How Much Pizza I Ate Last Night',
'width': 400,
'height': 300
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
The controller Code
public ActionResult GetMyChart1(string CurrentClass)
{
var tests = from t in db.Tests
group t by new { t.StudentID, t.Student.CurrentSchoolGrade } into tl
select new { StudentID = tl.Key.StudentID, Class = tl.Key.CurrentSchoolGrade, Score = (tl.Sum(k => k.Score)/tl.Sum(l => l.Part.Score))* 100, Count = tl.Count() };
var results = from t in tests
where t.Class == CurrentClass
select t;
List<DataItem> dt = new List<DataItem>();
dt.Add(new DataItem(results.Count(x => x.Score <= 40), "0% - 40%"));
dt.Add(new DataItem(results.Count(x => x.Score <= 60 && x.Score > 40), "40% - 60%"));
dt.Add(new DataItem(results.Count(x => x.Score <= 80 && x.Score > 60), "60% - 80%"));
dt.Add(new DataItem(results.Count(x => x.Score <= 100 && x.Score > 60), "80% - 100%"));
chartJson cj = new chartJson();
cj.rows = dt;
return Json(cj);
}
public class chartJson
{
public List<DataItem> rows { get; set; }
}
public class DataItem
{
public DataItem(int id, string name)
{
ID = id;
Name = name;
}
public int ID { get; set; }
public string Name { get; set; }
}
all the alerts returns correct values except alert(data.length); it returns undefined
and the drawing div appears with a label written in it No data
I am thinking that you need to move the chart drawing lines inside of the POST callback:
$.post('#Url.Content("~/Home/GetMyChart1")', function (items) {
// Successful requests get here
alert(JSON.stringify(items) + " - " + items.rows.length);
data.addRows(items.rows.length);
$.each(items.rows, function (i, item) {
alert(i);
data.setCell(i, 0, item.Name);
data.setCell(i, 1, item.ID);
});
alert("finished");
alert(data.length);
// Set chart options
var options = {
'title': 'How Much Pizza I Ate Last Night',
'width': 400,
'height': 300
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
};
Google charts API is written in JavaScript so it can be used with any web framework, including ASP.NET MVC. All that you need to do is to include it in your views. It shouldn't be limited or not work because you are using ASP.NET MVC.
After reviewing the full sample of code it looks like the google.setOnLoadCallback(drawChart); is most likely executing the drawChart method before the data is ready. Thus no chart.
Instead of making an Ajax .Post to the server to retrieve data, just build your data on the initial request.