Trying to populate a JavaScript array with ActiveRecord data - ruby-on-rails

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.

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

What data structure is select2 expecting from the server and how should it be handled?

What data structure is select2 (v4.0.3) expecting from the server and how should it be handled?
The question is asked on the official FAQ here, but there is no answer.
I have tried several variations of data structure, but based on this tutorial and this jsFiddle, have assumed what should be returned from the server is a list/array of objects/dicts, eg:
matches = [{"id":"1", "tag":"Python"},{"id":"2", "tag":"Javascript"},{"id":"3", "tag":"MongoDB"}]
I have tried this format with the following Javascript:
$("#my_select").select2({
ajax: {
url: "/tag_search",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data.matches
};
},
cache: true
},
minimumInputLength: 2,
tags: true,
tokenSeparators: [",", " "],
maximumSelectionLength: 5
});
Firebug results for search on Py:
The search area just displays this:
I am expecting all matches to be showing in the dropdown below the search area.
Solution that worked for me:
Rename json key (it has to be text), so server response is:
[{"text": "Python", "id": 1}]
(after coming across this document).
I also just returned the list itself from the server, rather than making the list a dict value.
Javascript
$("#my_select").select2({
ajax: {
url: "/tag_search",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 2,
tags: true,
tokenSeparators: [",", " "],
maximumSelectionLength: 5
});

Change Min and Max values in Kendo RadialGauge with Ajax

I want to be able to change the min and max values in the Kendo RadialGauge "on the fly" with ajax. Do I need to destroy the gauge first and create a new one, or could I possibly just change current gauge and redraw it with min, max, and pointer values?
I have a typical gauge using Razor engine:
#(Html.Kendo().RadialGauge()
.Name("TotalCostGauge")
.Pointer(pointer => pointer.Value(0))
.Scale(scale => scale
.MinorUnit(5)
.StartAngle(-50)
.EndAngle(230)
.Max(100)
.Labels(labels => labels.Position(GaugeRadialScaleLabelsPosition.Inside))
.Ranges(ranges =>
{
ranges.Add().From(180).To(180).Color("#c20000");
}
)
)
)
Using ajax I want to be able to update those values:
$.ajax({
type: "GET",
dataType: "json",
url: 'Controller/GetStuff/',
success: function (data) {
var totalCostGauge = $("#TotalCostGauge").data("kendoRadialGauge");
var totCostOptions = totalCostGauge.options;
//TODO: I want to be able to do something like this
totCostOptions.scale.max = data.Max;
totalCostGauge.value(data.TotalCost);
totalCostGauge.redraw();
},
error: function (error) {
}
});
I went through the documentation and could not see that the Min and Max values could be changed, however the pointer value can be changed via ajax.
Eventually I found out that I was going at this all wrong. This is actually what I needed to do:
$.ajax({
type: "GET",
dataType: "json",
url: 'Controller/GetStuff/',
success: function (data) {
$("#TotalCostGauge").kendoRadialGauge({
scale: {
max: data.Max, // This is actually what I should have done :)
startAngle: -50,
endAngle: 230,
labels: {
format: "C0",
font: "8px Arial,Helvetica,sans-serif"
},
ranges: [{
from: 0,
to: 0,
color: "green"
}]
}
});
var totalCostGauge = $("#TotalCostGauge").data("kendoRadialGauge");
totalCostGauge.value(data.Cost);
totalCostGauge.redraw();
},
error: function (error) {
}
});

How to retrieve a variable in jquery ajax .done()

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

Autocomplete in Jqgrid returns Data from Server but dont know to put in View

This is my first post. stackoverflow is a wonderful place for developers. Here is my issue.
I am trying to use Autocomplete in JqGrid Edit Form. i successfully retrieved data from server using ajax call but dont know how to display it in the view. below is my code.
FrontEnd Code:
colModel :[
{name:'prf_articlename', index:'prf_articlename', width:90, editable:true, edittype:'text',
editoptions: {
dataInit:function(e){
$(e).autocomplete({
source: function(request, response,term) {
var param = request.term;
$.ajax({
url: '/Myelclass/AutoCompleteServlet.do?term='+param+"&action="+"artname",
success: function (data) {
response($.map(data, function(item) {
return {
label: item.label,
};
}));//END Success
},
});//END AJAX
},
minLength: 2,
});//END AUOTOCOMPLETE
}//END Dataint
}//END Dataint
},
BackEnd Code:
String term = request.getParameter("term");
List<AutoComplete> articlelist = prfbo.getArticleNameinEditGrid(term);
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
Any one help on this???
This is what I personally use in my project:
Inside colModel:
dataInit: function (elem) { NameSearch(elem) }},
The function:
function NameSearch(elem) {
$(elem).autocomplete({ source: '/Controller/NameSearch',
minLength: 2, autosearch: true,
select: function (event, ui) {
$(elem).val(ui.item.value);
$(elem).focus().trigger({ type: 'keypress', charCode: 13 });
}
})//$(elem).autocomplete
$(elem).keypress(function (e) {
if (!e) e = window.event;
if (e.keyCode == '13') {
setTimeout(function () { $(elem).autocomplete('close'); }, 500);
return false;
}
})//$(elem).keypress(function (e){
} //function NameSearch(elem) {
I'm also dealing with an Enter key press as well in the above function.
here is the complete code for my Autocomplete in jqgrid Edit form..
colModel :[
{name:'name', index:'name', width:90, align:'center', editable:true, hidden: false, edittype:'text',
editoptions:{
dataInit:function (elem) {
$(elem).autocomplete({
minLength: 2,
source: function(request, response,term) {
var param = request.term; //values we enter to filter autocomplete
$.ajax({
url: "myurl",
dataType: "json",
type:"GET",
success: function (data) {
response($.map(data, function(item) {
return {
//can add number of attributes here
id: item.id,
shform: item.shortform,
value: item.name,
clr : item.color, //here apart from name and id i am adding other values too
size: item.size,
remar:item.remarks,
subs: item.subs,
selec:item.selec ,
};
}));//END Response
},//END Success
});//END AJAX
},
select: function( event, ui ) {
// setting values to textbox in jqgrid edit form based on selected values
$('#textbox1').val(ui.item.id);
$('#textbox2').val(ui.item.shform);
$('#textbox3').val(ui.item.clr);
$('#textbox4').val(ui.item.size);
$('#textbox5').val(ui.item.sizeremar);
$('#textbox6').val(ui.item.subs);
$('#textbox7').val(ui.item.selec);
$('#textbox8').val(ui.item.selp);
}
});
$('.ui-autocomplete').css('zIndex',1000); // if autocomplete has misalignment so we are manually setting it
}
}, editrules :{required : true},
formoptions:{rowpos: 1, colpos: 2}
},
........
]
server code :
String term = request.getParameter("term");
List<ArticleDetails> articlelist = prfbo.getPrfArticleName(term); //DB call via BO and DAO class
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
hope some one find it useful.

Resources