Flot.js & JQuery.Ajax: Create graph from key-value-pair - javascript

I'm trying to create a graph in mvc using flot.js. The graph will be a line graph with 3 lines on it. I have created a set of 3 list keyvaluepair with date/value to be plotted on the graph as shown in the code below. Currently i get : JavaScript runtime error: 'listvoltage' is undefined
Here's what I tried already:
Index.cshtml:
#if (Model != null)
{
foreach (var item in Model.BatteryInfo)
{
var listvoltage = new List<KeyValuePair<double, int>>();
var listtemperature = new List<KeyValuePair<double, int>>();
var listlevel = new List<KeyValuePair<double, int>>();
listvoltage.Add(new KeyValuePair<double, int>(
TMTMonitorAndCompare_Helpers.DateTimeHelpers.DateTimeToUnixTimestamp(item.TEST_DATE), Convert.ToInt32(item.battery_voltage)));
listtemperature.Add(new KeyValuePair<double, int>(
TMTMonitorAndCompare_Helpers.DateTimeHelpers.DateTimeToUnixTimestamp(item.TEST_DATE), Convert.ToInt32(item.battery_temperature)));
listlevel.Add(new KeyValuePair<double, int>(
TMTMonitorAndCompare_Helpers.DateTimeHelpers.DateTimeToUnixTimestamp(item.TEST_DATE), Convert.ToInt32(item.battery_level)));
CustomGraphinScript.js
$(document).ready(function () {
$.plot($("#placeholder"), listvoltage, { yaxis: { max: 1000 } });
});
Could anyone tell me what I need to do to the above to display this data on graph? is ajax required?

Razor file is executing on the server side. flot.js is executing on client/browser and they dont share the same type system. Thats why 'listvoltage' is undefined.
Put this in your razorfile. Lookout for Date conversion between .NET and Javascript. flot.js need Javascript timestamp.
#using System.Web.Script.Serialization
<script>
#{
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(listvoltage);
}
var timeserie = #Html.Raw(json);
</script>
Consider a Web API solution with JSON result and Ajax call.

Related

Not Showing the output of Json Data from controller to the view

I am trying to to show the Json data from controller to the view. It works fine in my test project, but when I copied the work in the main project it gives error.
It says Url does not exist in the current context. Although it works fine in the test project and doesn't give this error.
Controller Code -
public JsonResult GetFreight()
{
string url = "https://digitalapi.auspost.com.au/postage/parcel/domestic/calculate.json?length=22&to_postcode=3000&from_postcode=2000&weight=1.5&height=7.7&width=16&service_code=AUS_PARCEL_REGULAR";
//synchronous client.
var client = new WebClient();
client.Headers.Add("auth-key:a1234567-abcd-abcd-1234-1234567890abc");
var content = client.DownloadString(url);
var serializer = new JavaScriptSerializer();
var jsonContent = serializer.Deserialize<Object>(content);
return Json(jsonContent, JsonRequestBehavior.AllowGet);
}
View Code
<script>
var weather = Object();
$(document).ready(function () {
$.get("#Url.Action("GetFreight", "ShoppingCart")", function (response) {
//response
console.log(response);
weather = ko.mapping.fromJS(response); //populate the weather object
ko.applyBindings(weather);
});
});
</script>
<td>Freight = <span data-bind="text:postage_result.total_cost"></span></td>
I want to mention one more thing- In the main project the view is placed in another subfolder called "ShoppingCart" so do I need to change anything in the script when calling the method from the controller? Any help will be appreciated.
Thanks.

How to send JSON data created by Python to JavaScript?

I am using Python cherrypy and Jinja to serve my web pages. I have two Python files: Main.py (handle web pages) and search.py (server-side functions).
I create a dynamic dropdown list (using JavaScript) based on a local JSON file called component.json(created by function componentSelectBar inside search.py).
I want to ask how can my JavaScript retrieve JSON data without physically storing the JSON data into my local website root's folder and still fulfil the function of dynamic dropdown list.
The componentSelectBar function inside search.py:
def componentSelectBar(self, brand, category):
args = [brand, category]
self.myCursor.callproc('findComponent', args)
for result in self.myCursor.stored_results():
component = result.fetchall()
if (len(component) == 0):
print "component not found"
return "no"
components = []
for com in component:
t = unicodedata.normalize('NFKD', com[0]).encode('ascii', 'ignore')
components.append(t)
j = json.dumps(components)
rowarraysFile = 'public/json/component.json'
f = open(rowarraysFile, 'w')
print >> f, j
print "finish component bar"
return "ok"
The selectBar.js:
$.getJSON("static/json/component.json", function (result) {
console.log("retrieve component list");
console.log("where am i");
$.each(result, function (i, word) {
$("#component").append("<option>"+word+"</option>");
});
});
store results from componentSelectBar into database
expose new api to get results from database and return json to browser
demo here:
#cherrypy.expose
def codeSearch(self, modelNumber, category, brand):
...
result = self.search.componentSelectBar(cherrypy.session['brand'], cherrypy.session['category'])
# here store result into a database, for example, brand_category_search_result
...
#cherrypy.expose
#cherrypy.tools.json_out()
def getSearchResult(self, category, brand):
# load json from that database, here is brand_category_search_result
a_json = loadSearchResult(category, brand)
return a_json
document on CherryPy, hope helps:
Encoding response
In your broswer, you need to GET /getSearchResult for json:
$.getJSON("/getSearchResult/<arguments here>", function (result) {
console.log("retrieve component list");
console.log("where am i");
$.each(result, function (i, word) {
$("#component").append("<option>"+word+"</option>");
});
});
To use that json data directly into javascript you can use
var response = JSON.parse(component);
console.log(component); //prints
OR
You already created json file.If that file is in right format then you can read json data from that file using jQuery jQuery.getJSON() For more: http://api.jquery.com/jQuery.getJSON/
You are rendering a HTML and sending it as response. If you wish to do with JSON, this has to change. You should return JSON in your main.py, whereas you will send a HTML(GET or POST) from Javascript and render it back.
def componentSelectBar(self, brand, category):
/* Your code goes here */
j = json.dumps(components)
// Code to add a persistent store here
rowarraysFile = 'public/json/component.json'
f = open(rowarraysFile, 'w')
print >> f, j
// Better to use append mode and append the contents to the file in python
return j //Instead of string ok
#cherrypy.expose
def codeSearch(self):
json_request = cherrypy.request.body.read()
import json # This should go to the top of the file
input_dict = json.loads(json_request)
modelNumber = input_dict.get("modelNumber", "")
category = input_dict.get("category", "")
brand = input_dict.get("brand", "")
/* Your code goes here */
json_response = self.search.componentSelectBar(cherrypy.session['brand'], cherrypy.session['category'])
return json_response
Here, I added only for the successful scenario. However, you should manage the failure scenarios(a JSON error response that could give as much detail as possible) in the componentSelectBar function. That will help you keep the codeSearch function as plain as possible and help in a long run(read maintaining the code).
And I would suggest you to read PEP 8 and apply it to the code as it is kind of norm for all python programmers and help any one else who touches your code.
EDIT: This is a sample javascript function that will make a post request and get the JSON response:
searchResponse: function(){
$.ajax({
url: 'http://localhost:8080/codeSearch', // Add your URL here
data: {"brand" : "Levis", "category" : "pants"}
async: False,
success: function(search_response) {
response_json = JSON.parse(search_response)
alert(response_json)
// Do what you have to do here;
// In this specific case, you have to generate table or any structure based on the response received
}
})
}

Model is null when I'm trying to use it in JavaScript

My app arhitecture is ASP.Net MVC
I'm trying to pass some data from the mssql server using entity framework ORM.
This is the code from my action.
public ActionResult Create()
{
List<object> myModel = new List<object>();
var places = db.Places.Where(p => p.UserId == User.Identity.GetUserId());
myModel.Add(places);
myModel.Add(new Place());
ViewBag.UserId = new SelectList(db.AspNetUsers, "Id", "UserName");
return View(myModel);
}
The code from my view
#model IEnumerable<object>
#{
List<WhereWeDoIt.Models.Place> places = Model.ToList()[0] as List<WhereWeDoIt.Models.Place>;
WhereWeDoIt.Models.Place place = Model.ToList()[1] as WhereWeDoIt.Models.Place;
ViewBag.Title = "Create";
}
...
<script type="text/javascript">
//Users data
var json = #Html.Raw(Json.Encode(places));
console.log("Places test " + json);
</script>
...
The console will output "null"
What am I doing wrong?
Once Html.Raw will get the string and put it directly in the html, try
to put the #Html.Raw between single quotes like:
var json = '#Html.Raw(Json.Encode(places))';
Regards,
The solution that I've provided above will set the json to json string (not object) so will not work, sorry about that. Below there is the solution (simulated and tested in my machine)
Well, we have some things going on here.
I have accomplished success in the code doing so:
#model IEnumerable<object>
#{
var places = Model.ToList()[0];
HypothesisWebMVC.Models.Place place = Model.ToList()[1] as HypothesisWebMVC.Models.Place;
ViewBag.Title = "Create";
}
<script type="text/javascript">
//Users data
var json = #Html.Raw(Json.Encode(places));
console.log("Places test " + json);
</script>
This code will set the json variable to a an object (the places list set in the controller).
I don't know what are your goal but that code that I´ve posted above will work.
Some considerations:
In the actions, when you do:
List<object> myModel = new List<object>();
var places = db.Places.Where(p => p.UserId == User.Identity.GetUserId());
myModel.Add(places);
myModel.Add(new Place());
You're creating an myModel that will have in the first position and list (or IQueryable) of Place, and in the second position a single place (not a list), so you can not convert the whole model to a list.
You could use:
List<WhereWeDoIt.Models.Place> places = Model.ToList()[0] as List<WhereWeDoIt.Models.Place>;
By, when adding to the model, do a .ToList() before inserting.
Consider using a view model (an object created specific for the view)
Hope I've helped.
Regards,
I test your code. Edit view like this:
List<WhereWeDoIt.Models.Place> places = Model.ToList() as List<WhereWeDoIt.Models.Place>;
Model.ToList()[0] is not list.

ASP Web Pages Razor using AJAX to return array from Database

I'm working with ASP for my coursework and I am using Razor Web Pages to do an application. Now, I would like some help with retrieving information from the SQL database.
As it stands I make an ajax call like this:
$.ajax({
type: "POST",
url: "/timetabler/Includes/ajaxModulesByUserId",
data: { id: UserId },
success: function (data) {
alert(data);
if (data == "ERROR") {
alert("We are unable to store the theme you have selected, therefore the change will not be permanent.");
}
}
});
This quite simply calls ajaxModulesByUserId.cshtml passing a userID of like 1. Now this calls the file fantastically.
Now what I'm trying to do in my CSHTML is take the requested ID, then use my C# function:
public IEnumerable<dynamic> getAllQuery(string query)
{
return _db.Query(query);
}
To execute my query.
Now I call it in my Razor code like this:
string input = "";
input = Request["id"];
var arr = new List<string>();
if (!string.IsNullOrEmpty(input))
{
// Add new sheet to database
using (var repo = new initDatabase("SQLServerConnectionString"))
{
foreach (var row in repo.getAllQuery("SELECT * FROM Module WHERE userID = " + input))
{
arr.Add(""+row.moduleCode+","+row.moduleTitle+"");
}
#session.Serialize(arr);
}
}
So I return the rows from the database and put them into an array, now my problem is, getting those values to the javascript.
As it stands I'm using a trick I read from here Stackoverflow, by using a function like this:
public static string Serialize(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
This will actually let me see the values in Javascript, but I'm getting stuck as I end up with values like this:
How can I receive a clean array? and possibly even return ALL the rows from the database as I've had to do a messy way of passing the code and title in 1 array field but separated by a comma.
Would really appreciate it if you could help me get my output correct.
Thanks
The Web Pages framework includes a Json helper which can take your data and return it as JSON.
if (!Request["id"].IsEmpty())
{
using (var repo = new initDatabase("SQLServerConnectionString"))
{
var data = repo.getAllQuery("SELECT * FROM Module WHERE userID = #0", Request["id"])
Json.Write(data, Response.Output);
}
}

How to make YUI datasource parse Null values in the dataset?

I am using YUI datatable and datasource to render data in one of my projects. The data returned happens to be NULL and YUI datasource is unable to parse it.
Below is the declaration code of datasource and datatable. For readability sake, I am seperating each of the declarations.
Column Descriptions declaration
var columnDescription =
[
{key:'Requirements'},
{key:'abc'},
{key:'xyz'}
];
This columnDescription is set in the function below.
DataSource Declaration
var dataSrcSample = new YAHOO.util.FunctionDataSource(getDataGrid);
myDataSource.connMethodPost = true;
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.responseSchema = {
fields:['Requirements',
{key:'abc',parser:YAHOO.util.DataSource.parseString},
{key:'xyz',parser:YAHOO.util.DataSource.parseString}]
};
getDataGrid function makes the call to server side to get the data from the server.
Below is the table definition itself.
YAHOO.example.sampleTable = function()
{
var columnDesc=columnDescription;
var myDataSource = dataSrcSample;
var oConfigs =
{
width:'100%'
};
var myDataTable = new YAHOO.widget.DataTable("tableContainerDiv", columnDesc, myDataSource, oConfigs);
}();
tableContainerDiv is declared in the html page. This is the container div.
The function that gets the JSON data from server.
function getDataGrid()
{
//calls backend and gets the data
}
The function is returning json string that has some null values. Datasource constructor is complaining following problems.
ERROR_DATAINVALID
ERROR_DATANULL
I checked the yui documentation and found that the string parser does not parse null values. I am wondering if there is any way to parse this data. Do I have to handleResponse parse the raw data? Any suggestions appreciated.
You need to create your own parser perhaps?
function parseNull(value) {
// This exact logic may be incorrect, depends on what you get for value in the null case
if (value=='null') {
return null;
}
YAHOO.util.DataSource.parseString(value);
}
Then you can specify:
{key:'abc',parser:parseNull}
To use your new parser

Categories

Resources