How to retrieve a variable in jquery ajax .done() - asp.net-mvc

Stackoverflow(ers),
I have created a javascript function in which to process data from an array of objects, and in this function I am iterating through the array calling an ajax request for each object in the array.
However, inside the ajax.done() function, I need to pass in the index of the iteration, j. Inside the iteration, however, j is stuck on 4, whereas outside the iteration, j counts successfully with the iteration. Note that the i iteration in the code below loops through inside each ajax request to pull out certain values to form an array, so can be ignored.
Can anyone help me in working out what I need to do to make j iterate inside the .done() block?
Thanks,
Jamie
Object Passed To Code:
var dataConfig = [
{ targetDiv: "#chart", chartTitle: "Title", tooltipVisible: true, xAxisLabel: "Label", leftYAxisLabel: "Unit" },
{ apiUrl: "URL", type: "column", yAxis: "right", visibleInLegend: false },
{ apiUrl: "URL", type: "line", yAxis: "left", visibleInLegend: false },
{ apiUrl: "URL", type: "line", yAxis: "left", visibleInLegend: false },
];
The Code:
for ( var j = 2; j < dataConfig.length; j++ ) {
console.log(j);
chartConfig[j] = {
yAxisValues: [],
type: dataConfig[j].type,
yAxis: dataConfig[j].yAxis,
visibleInLegend: dataConfig[j].visibleInLegend
}
$.ajax({
url: baseURL + dataConfig[j].apiUrl,
beforeSend: function ( xhr ) {
xhr.setRequestHeader('Authorization', 'yes');
}
}).done(function (data) {
//get Y Axis Values
var yAxisData = data.DataSeries.Data;
yAxisValues = [];
for ( var i = 0; i < yAxisData.length; i++ ) {
var yAxisValue = yAxisData[i].Y[0];
yAxisValues.push(parseInt(yAxisValue, 10));
};
console.log(yAxisValues);
console.log("j:", j);
// chartConfig[j].yAxisValues = yAxisValues;
});
};

AJAX is asynchronous. The .done() method will run at a point that is most likely out of sync with the parent for loop, thus you can't rely on the variable 'j'.
You can use the following syntax to achieve what you want to by capturing the value of j in a self executing function:
for ( var j = 2; j < dataConfig.length; j++ ) {
(function(index) {
$.ajax({
url: baseURL + dataConfig[j].apiUrl,
beforeSend: ...
}).done(function(data) {
console.log(index);
});
})(j);
}

Related

C3 Charts in C# html

Recently im working on c3 charts its actually working great
but i had a problem with dynamically get multiple data in DB
Multiple XY Lines chart
X had to be in string
I actually want multiple xy values and x values had to be string
After a long period i dont get any ideas
I tried json method in ajax
$.ajax({
type: "POST",
url: "../Home/timechart",
data: Getdata,
contentType: "application/json; chartset=utf-8",
dataType: "json",
success: function (response) {
successClass(response)
},
});
function successClass(jsondata) {
var data = {};
var mvalue = [];
var mdatetime = [];
var TagID = [];
jsondata.forEach(function (e) {
mvalue.push(e.mvalue);
mdatetime.push(e.mdatetime);
if (TagID != e.TagID) {
TagID.push(e.TagID);
}
})
//alert(objvalue)
// alert(objdate)
var chart = c3.generate({
bindto: '#chart',
data: {
columns: [
/* ['x'].concat(mdatetime),*/
[TagID].concat(mvalue)
]
},
axis: {
x: {
type: 'category',
categories: mdatetime,
tick: {
rotate: -25,
multiline: false
},
height: 130
}
},
legend: {
position: 'outer-center'
}
});
}
}
});
});
i can get a chart in single dynamic value but dont know how to get multiple y values and same x value in it

How can I get the selected checkbox in kendo grid?

I have Kendogrid grid that I get the data by JSON for the URL that I have and activate Selection mode as I found the kendo grid documentation, but I am trying to get the selected data from kendo grid, try some methods in javascript but not yet I have been able to do it. If someone can help me?
$(document).ready(function () {
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
fileName: "user.xlsx",
filterable: true
},
dataSource: {
transport: {
read: {
url: `/user`
}
},
schema: {
data: function (response) {
return response.permisos;
},
model: {
fields: {
id: { type: "number" },
nombre: { type: "string" },
descripcion: { type: "string" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: false,
sortable: true,
filterable: true,
pageable: true,
persistSelection: true,
change: onChange,
columns: [
{ selectable: true, width: "50px" },
{ field: "id", title: "Id" },
{ field: "nombre", title: "Nombre" },
{ field: "descripcion", title: "DescripciĆ³n" }
]
});
$("#grid").data("kendoGrid").wrapper.find(".k-grid-header-wrap").off("scroll.kendoGrid");
});
I found two solutions, the first one is activating the change: onchange, one can obtain the selected checkboxes, each time one selects. What I'm doing is going through the checkboxes and saving them in a list
function onchange(e) {
var permiso = [];
var numero = 0;
var rows = e.sender.select();
rows.each(function (e) {
var grid = $("#grid").data("kendogrid");
var dataitem = grid.dataitem(this);
var recibir = dataitem;
console.log(dataitem);
console.log("dato recibido" + recibir.id);
permiso.push(recibir.id);
})
console.log("largo: " + permiso.length);
for (var i = 0; i < permiso.length; i++) {
console.log("array: " + permiso[i]);
}
And the other way is that you added a button that activates the event to go through the grid to get the checkbox, which is the best for me
$("#saveChanges").kendoButton({
click: function (e) {
var permiso = [];
var entityGrid = $("#grid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function (index, row) {
var selectedItem = entityGrid.dataItem(row);
var recibir = selectedItem;
console.log(selectedItem);
console.log("Dato recibido rows.each" + recibir.id);
permiso.push(recibir.id);
});
for (var i = 0; i < permiso.length; i++) {
console.log("List obtenido por el boton: " + permiso[i]);
}
var RolPermisos = { rolId: $("#IdRol").val() , permisos: permiso };
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../../Roles/api/Ui/',
dataType: 'json',
data: $.toJSON(lineItems),
success: function (result) {
if (result) {
alert('Success');
}
else {
alert('Failure');
}
}
});
}
})
My English is not so good, I hope you get the answer.

Trying to populate a JavaScript array with ActiveRecord data

So I'm using a chart to display the top most common operating systems (e.g. XP, server 2003, etc.) and I'm trying to pull this information from ActiveRecord. I have a Node model that has the operating_system column.
From my show page, this is what I have at the bottom:
var chart = c3.generate({
bindto: '#nodes-os-chart',
title: {
text: 'Top 5 Operating Systems Detected'
},
data: {
columns: [
['Microsoft Windows XP', 10],
['Microsoft Windows Server 2003', 5],
['Microsoft Windows Server 2016', 15]
],
type : 'pie',
onclick: function (d, i) { console.log("onclick", d, i); },
onmouseover: function (d, i) { console.log("onmouseover", d, i); },
onmouseout: function (d, i) { console.log("onmouseout", d, i); }
},
legend: {
position: "right"
}
});
However, I would like to fill in the columns array with some data from ActiveRecord, so I tried turning it into an ajax call, such as this:
var operating_systems = $.ajax({
url: window.location.pathname + "/node_os",
type: 'GET',
dataType: 'json', // added data type
success: function(res) {
console.log(res);
alert(res);
}
});
var chart = c3.generate({
bindto: '#nodes-os-chart',
title: {
text: 'Top 5 Operating Systems'
},
data: {
columns: operating_systems,
type : 'pie',
onclick: function (d, i) { console.log("onclick", d, i); },
onmouseover: function (d, i) { console.log("onmouseover", d, i); },
onmouseout: function (d, i) { console.log("onmouseout", d, i); }
},
legend: {
position: "right"
}
});
I added a route for get 'node_os' to map back to the necessary controller. However, now in the controller, this is the method I have defined for node_os:
# GET /logs/4/node_os
def node_os
return ['Test1','Test2']
end
Test1 and Test2 are just samples, but I'm trying to figure out the best way to do this. I get a pop up that says "Undefined" when I try to run this in the browser.
Solved this using this: https://medium.com/#ryannovas/pass-a-nested-array-from-rails-to-js-41f021eef459.
Basically my show.html.erb just makes the AJAX call and the rest happens in the js.erb file.

use Highcharts Api to show multiples values

Hi everyone I am new using highcharts, I have my data structure and when I try to show, I don't see anything
function nueva (current_data){
var seriesOptions = [],
seriesCounter = 0,
type = ['jobs_running', 'jobs_pending'];
function createChart() {
$('#containerChart').highcharts('StockChart', {
rangeSelector: {
selected: 4
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
}
for (var j = 0; j < current_data['names'].length; j++){
var all_element = []
name_project = current_data['names'][j];
for (var i = 0; i < type.length; i++){
seriesCounter = 0;
for (var i = 0; i < type.length; i++){
seriesOptions[j] = {
name: type[i],
data: current_data[name_project][type[i]],
};
}
}
createChart();
}
}
I pass current_data to my function that is like this
I want to show 'jobs_running' and 'jobs_pendding' I set the value to seriesOptions
and my array of data has this
Any idea why I don't see anything in the chart! I am missing something.
Thanks in advance
Hopefully you can find your answer in this:
https://jsfiddle.net/ekekp8rh/1/
Not sure what you were hoping to get but at least this displays a chart.
var data = {
projects: [{
name: 'Project X',
jobs_running: [
[1459814400000, 121],
[1459900800000, 205],
[1459987200000, 155],
[1460073600000, 458]
],
jobs_pending: [
[1459814400000, 146],
[1459900800000, 149],
[1459987200000, 158],
[1460073600000, 184]
]
}, {
name: 'Project Y',
jobs_running: [
[1459814400000, 221],
[1459900800000, 295],
[1459987200000, 255],
[1460073600000, 258]
],
jobs_pending: [
[1459814400000, 246],
[1459900800000, 249],
[1459987200000, 258],
[1460073600000, 284]
]
}]
};
nueva(data);
function nueva(current_data) {
var seriesOptions = [],
type = ['jobs_running', 'jobs_pending'];
for (var j = 0; j < current_data['projects'].length; j++) {
var project = current_data['projects'][j];
for (var i = 0; i < type.length; i++) {
seriesOptions.push({
name: project.name + ' ' + type[i],
data: project[type[i]]
});
}
}
$('#containerChart').highcharts('StockChart', {
series: seriesOptions
});
}

Can I populate a variable in Knockout and then set it to a hidden variable of my model?

Using MVC 4, I am populating a variable with knockout (in a razor view), and I want to pass that variable back to my controller through my viewmodel. For example
var selectedProgramOptions;
$.ajax({
type: "GET",
contentType: "application/json",
dataType: "jsonp",
url: ceraSvcUrl + "/api/Registrations/GetRegistrationOptions?regId=#Model.Registration.Id",
success: function (result) {
selectedProgramOptions = result;
$.ajax({
type: "GET",
contentType: "application/json",
dataType: "jsonp",
url: ceraSvcUrl + "/api/Programs/GetProgramOptions?programId=#Model.Registration.Program.Id",
success: function (allProgsResult) {
if (allProgsResult.length == 0)
$('#programOptionsDiv').hide();
for (var i = 0; i < allProgsResult.length; i++) {
var match = false;
for (var j = 0; j < selectedProgramOptions.length; j++) {
if (allProgsResult[i].Name == selectedProgramOptions[j].Name) {
match = true;
self.AvailableOptions.push(new ProgramOption(selectedProgramOptions[j].Name, selectedProgramOptions[j].ChargeCode, selectedProgramOptions[j].Price, true, selectedProgramOptions[j].Notes, selectedProgramOptions[j].OptionGroup));
}
}
var chgCode = allProgsResult[i].ChargeCode;
if (match == false && ["TG", "TN", "TP", "TV", "TW", "E2", "E3", "L2", "L3"].indexOf(chgCode) <= -1)
self.AvailableOptions.push(new ProgramOption(allProgsResult[i].Name, allProgsResult[i].ChargeCode, allProgsResult[i].Price, false, allProgsResult[i].Notes, allProgsResult[i].OptionGroup));
}
}
});
}
});
This is the code to populate the knockout field is the self.AvailableOptions. I need to put that field into #Model.Registration.AvailableOptions.

Resources