I'm trying to create a network using the vis.js library (http://visjs.org/) and django (the basic one - http://visjs.org/examples/network/basicUsage.html).
I need to pass data specifying the nodes of the network from django to javascript.
This is my views.py:
def create_network(request):
r=[]
for i in range(1,6):
d={}
d['id'] = i
d['label'] = 'Node ' + str(i)
r.append(d)
data = json.dumps(r)
return render(request, 'network.html', {"nodes":data})
This is the relevant part of my template:
n = {{ nodes }}
var nodes = new vis.DataSet(n);
When I run this, the {{nodes}} disappears and it simply becomes:
n =
var nodes = new vis.DataSet(n);
and I get unexpected token errors.
I'm relatively new to Django and javascript so sorry if this seems elemenatary. How would I fix this? Thanks.
Try the following:
var n = `{{ nodes|safe }}`;
var nodes = new vis.DataSet(n);
You may or may not need to add a jQuery.parseJSON() around the data before passing it into the vis.DataSet. I cannot say for sure because I have never used http://visjs.org/.
Related
I'm trying to build a UI with two dropdowns. The first one is "category", the second one is "sub-category". I can build a static list of "category" in my razor view. I want the "sub-category" item list to be dynamically updated when "category" is changed. I'm trying to pass all category information from server side to client side since the list is not big and there is no security issue. But I cannot find a good way to format my data and transfer it to client side. I can generate a json object with all of my category trees using the following code:
ExpandoObject catToSubcatMap = new ExpandoObject();
foreach (var cat in repository.Categories)
{
var subcats = repository.SubCategories.Where(s => s.ParentID == cat.CategoryID);
List<Object> subcatNameList = new List<object>();
foreach(var subcat in subcats)
{
subcatNameList.Add(new { Name = subcat.Name });
}
AddProperty(catToSubcatMap, cat.Name, subcatNameList);
}
Session["CatToSubcatMap"] = JsonConvert.SerializeObject(catToSubcatMap, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
The json itself looks perfect. But when I tried to read the value from my jQuery function, it failed:
var sss = '#Session["CatToSubcatMap"]';
It seems like there are too many special characters in the json string. My generic question is: how should I format and pass complicated data between server and client. Using Viewbag or Session, which one is preferred?
Thanks
Chris
You can do what you are trying to do; what you have should be formatted correctly, but you just have to include Html.Raw.
var sss = #(
Html.Raw(Session["CatToSubcatMap"].ToString())
);
Raw will essentially write out directly to the response without encoding the contents, which is what likely was happening.
I have a function in JavaScript
function functioncalled(){
var result = 1;
var activityID = {{ mynames[result][8] }};
console.log(activityID);
}
mynames is a list of lists in Flask template. The above code fails giving me an error - UndefinedError: list object has no element Undefined. But when I access the list element using var activityId = {{mynames[1][8]}} everything works fine. How do I make this work? Is there a workaround? I couldn't find the solution anywhere.
You will not be able to do that, because {{any_flask_variable}}is evaluated on server side and rendered HTML is sent to browser where all javascript runs. At the time of evaluation on the server there is not browser to run javascript code. The best way to resolve this is to assign the list variable to var result.
function functioncalled(){
var result = {{mynames}};
// Here you can access the variable result
console.log(activityID);
}
That off course after assuming that mynames variable can be mapped to js array of arrays.
using https://www.npmjs.com/package/slack-client
expects you to make an extra file just for the token and to get it you must do
process.env.SLACK_API_TOKEN
I don't like this approach of creating a file just for the sake of a token!
My code is server side, already in a directory that users cannot see so I would like to just write the token into the javascript as an object/string/array
I have so far failed with array
var token=[
'SLACK_TOKEN=xxxx'
, 'SLACK_CLIENT_ID=xxxx'
, 'SLACK_CLIENT_SECRET=xxxx'
];
and string
var token=
'SLACK_TOKEN=xxxx\n'
+ 'SLACK_CLIENT_ID=xxxx\n'
+ 'SLACK_CLIENT_SECRET=xxxx'
;
and object
var token={
SLACK_TOKEN:'xxxx'
, SLACK_CLIENT_ID:'xxxx'
, SLACK_CLIENT_SECRET:'xxxx'
};
Everyone else's apis just get you to put things like secret keys inside srings or objects like normal! How can I do this the normal way?
process.env.SLACK_API_TOKEN isn't a file, it's an environment variable. The advantage of keeping your API key there is that you can't accidentally commit it to version control. That said, the page you linked to makes it pretty clear that you don't have to use it:
var RtmClient = require('slack-client').RtmClient;
var token = process.env.SLACK_API_TOKEN || '';
var rtm = new RtmClient(token, {logLevel: 'debug'});
rtm.start();
Just set the token variable to your API token, then pass it as the first parameter to new RtmClient():
var RtmClient = require('slack-client').RtmClient;
var token = 'YOUR SLACK API TOKEN';
var rtm = new RtmClient(token, {logLevel: 'debug'});
rtm.start();
this looks a very trivial query but I can't seem to make it work..
I am trying to get for instance an object that has locationName = "NYC" AND groupName = "Adults". I am trying to query using this code I found on Parse documentation:
var groupQuery = new Parse.Query("MyTable");
groupQuery.equalTo("group", groupName);
var locationQuery = new Parse.Query("MyTable");
locationQuery.equalTo("location", locationName);
var mainQuery = Parse.Query.or(locationQuery, groupQuery);
But I obviously fail because I am using Parse.Query.or instead what should have been Parse.Query.and which, for some reason doesn't exist...
Is there any alternative way to do it, for some reason I cannot find it on the documentation..
Cheers
Parse queries use and by default, which is why there is only a Parse.Query.or().
What you want to do can simply be achieved this way :
var mainQuery = new Parse.Query("MyTable");
mainQuery.equalTo("group", groupName);
mainQuery.equalTo("location", locationName);
I'm trying to implement a REST interface under IIS5.1/ASP-classic (XP-Pro development box). So far, I cannot find the incantation required to retrieve request content variables under the PUT HTTP method.
With a request like:
PUT http://localhost/rest/default.asp?/record/1336
Department=Sales&Name=Jonathan%20Doe%203548
how do I read Department and Name values into my ASP code?
Request.Form appears to only support POST requests. Request.ServerVariables only gets me to header information. Request.QueryString doesn't get me to the content either...
Based on the replies from AnthonyWJones and ars I went down the BinaryRead path and came up with the first attempt below:
var byteCount = Request.TotalBytes;
var binContent = Request.BinaryRead(byteCount);
var myBinary = '';
var rst = Server.CreateObject('ADODB.Recordset');
rst.Fields.Append('myBinary', 201, byteCount);
rst.Open();
rst.AddNew();
rst('myBinary').AppendChunk(binContent);
rst.update();
var binaryString = rst('myBinary');
var contentString = binaryString.Value;
var parameters = {};
var pairs = HtmlDecode(contentString).split(/&/);
for(var pair in pairs) {
var param = pairs[pair].split(/=/);
parameters[param[0]] = decodeURI(param[1]);
}
This blog post by David Wang, and an HtmlDecode() function taken from Andy Oakley at blogs.msdn.com, also helped a lot.
Doing this splitting and escaping by hand, I'm sure there are a 1001 bugs in here but at least I'm moving again. Thanks.
Unfortunately ASP predates the REST concept by quite some years.
If you are going RESTFull then I would consider not using url encoded form data. Use XML instead. You will be able to accept an XML entity body with:-
Dim xml : Set xml = CreateObject("MSXML2.DOMDocument.3.0")
xml.async = false
xml.Load Request
Otherwise you will need to use BinaryRead on the Request object and then laboriously convert the byte array to text then parse the url encoding yourself along with decoding the escape sequences.
Try using the BinaryRead method in the Request object:
http://www.w3schools.com/ASP/met_binaryread.asp
Other options are to write an ASP server component or ISAPI filter:
http://www.codeproject.com/KB/asp/cookie.aspx