Retrieve data from list in SharePoint 2013 provider hosted App - sharepoint-2013

I have developed a provider hosted app in SharePoint 2013. As you already know, Visual Studio creates web application and SharePoint app. The web application gets hosted inside IIS and the SharePoint App in SharePoint site collection. I'm trying to get data from a list hosted in SharePoint using CSOM. But I get ran insecure content error.
"[blocked] The page at 'https://localhost:44302/Pages/Default.aspx?SPHostUrl=http%3A%2F%2Fecontent&0319c41%2Eecontent%2Eelibrary%2Eapps%2Elocal%2FSharePointApp2%5Fsingeltest'
was loaded over HTTPS, but ran insecure content from 'http://apps-892db5a0319c41.econtent.elibrary.apps.local/sharepointapp2_singeltest/_layouts/15/AppWebProxy.aspx': this content should also be loaded over HTTPS."
here is my code in Default.aspx
<script type="text/javascript" src="../Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript" src="../Scripts/MicrosoftAjax.js"></script>
<script type="text/javascript" src="../Scripts/SP.Core.js"></script>
<script type="text/javascript" src="../Scripts/INIT.JS"></script>
<script type="text/javascript" src="../Scripts/SP.Runtime.js"></script>
<script type="text/javascript" src="../Scripts/SP.js"></script>
<script type="text/javascript" src="../Scripts/SP.RequestExecutor.js"></script>
<script type="text/javascript" src="../Scripts/App.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Get title via CSOM" onclick="execCSOMTitleRequest()" /> <br />
<input id="Button2" type="button" value="Get Lists via CSOM" onclick="execCSOMListRequest()" />
</div>
<p ID="lblResultTitle"></p><br />
<p ID="lblResultLists"></p>
</form>
</body>
</html>
and App.js is:
var hostwebUrl;
var appwebUrl;
// Load the required SharePoint libraries
$(document).ready(function () {
//Get the URI decoded URLs.
hostwebUrl =
decodeURIComponent(
getQueryStringParameter("SPHostUrl")
);
appwebUrl =
decodeURIComponent(
getQueryStringParameter("SPAppWebUrl")
);
// resources are in URLs in the form:
// web_url/_layouts/15/resource
var scriptbase = hostwebUrl + "/_layouts/15/";
// Load the js files and continue to the successHandler
//$.getScript(scriptbase + "/MicrosoftAjax.js",
// function () {
// $.getScript(scriptbase + "SP.Core.js",
// function () {
// $.getScript(scriptbase + "INIT.JS",
// function () {
// $.getScript(scriptbase + "SP.Runtime.js",
// function () {
// $.getScript(scriptbase + "SP.js",
// function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest); }
// );
// }
// );
// });
// });
// });
});
function execCrossDomainRequest() {
alert("scripts loaded");
}
function getQueryStringParameter(paramToRetrieve) {
var params = document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
function execCSOMTitleRequest() {
var context;
var factory;
var appContextSite;
var collList;
//Get the client context of the AppWebUrl
context = new SP.ClientContext(appwebUrl);
//Get the ProxyWebRequestExecutorFactory
factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl);
//Assign the factory to the client context.
context.set_webRequestExecutorFactory(factory);
//Get the app context of the Host Web using the client context of the Application.
appContextSite = new SP.AppContextSite(context, hostwebUrl);
//Get the Web
this.web = context.get_web();
//Load Web.
context.load(this.web);
context.executeQueryAsync(
Function.createDelegate(this, successTitleHandlerCSOM),
Function.createDelegate(this, errorTitleHandlerCSOM)
);
//success Title
function successTitleHandlerCSOM(data) {
$('#lblResultTitle').html("<b>Via CSOM the title is:</b> " + this.web.get_title());
}
//Error Title
function errorTitleHandlerCSOM(data, errorCode, errorMessage) {
$('#lblResultLists').html("Could not complete CSOM call: " + errorMessage);
}
}
function execCSOMListRequest() {
var context;
var factory;
var appContextSite;
var collList;
//Get the client context of the AppWebUrl
context = new SP.ClientContext(appwebUrl);
//Get the ProxyWebRequestExecutorFactory
factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl);
//Assign the factory to the client context.
context.set_webRequestExecutorFactory(factory);
//Get the app context of the Host Web using the client context of the Application.
appContextSite = new SP.AppContextSite(context, hostwebUrl);
//Get the Web
this.web = context.get_web();
// Get the Web lists.
collList = this.web.get_lists();
//Load Lists.
context.load(collList);
context.executeQueryAsync(
Function.createDelegate(this, successListHandlerCSOM),
Function.createDelegate(this, errorListHandlerCSOM)
);
//Success Lists
function successListHandlerCSOM() {
var listEnumerator = collList.getEnumerator();
$('#lblResultLists').html("<b>Via CSOM the lists are:</b><br/>");
while (listEnumerator.moveNext()) {
var oList = listEnumerator.get_current();
$('#lblResultLists').append(oList.get_title() + " (" + oList.get_itemCount() + ")<br/>");
}
}
//Error Lists
function errorListHandlerCSOM(data, errorCode, errorMessage) {
$('#lblResultLists').html("Could not complete CSOM Call: " + errorMessage);
}
};
Any solution is appreciated.

well first off, i can tell you your decodeURIComponent logic isnt working.
Yours:https://localhost:44302/Pages/Default.aspx?SPHostUrl=http%3A%2F%2Fecontent&0319c41%2Eecontent%2Eelibrary%2Eapps%2Elocal%2FSharePointApp2%5Fsingeltest
Mine: https://localhost:44302/Pages/Default.aspx?SPHostUrl=http://econtent&0319c41.econtent.elibrary.apps.local/SharePointApp2_singeltest
Secondly, is the HostURL content supposed to be unsecure? If so, then you may want to change your browser settings. If not, then you need to see why your HostURL is in the Anonymous Zone but your AppURL is in the Secure Zone.
In either case, verify that Everyone has at least Read Access to the location your trying to pull from.
Last thing to do, is to setup a Trusted Host Location if you have access to the Admin Center.
Here is a code snippet for what i used to test:
$(document).ready(function () {
$.getScript(qsHostUrl + "/_layouts/15/SP.RequestExecutor.js", getHostInfo);
function getHostInfo() {
var ctxApp = new SP.ClientContext(qsAppUrl);
var factory = new SP.ProxyWebRequestExecutorFactory(qsAppUrl);
ctxApp.set_webRequestExecutorFactory(factory);
var ctxHost = new SP.AppContextSite(ctxApp, qsHostUrl);
var web = ctxHost.get_web();
ctxApp.load(web);
ctxApp.executeQueryAsync(
Function.createDelegate(this, getHostInfoSuccess),
Function.createDelegate(this, getHostInfoError)
);
function getHostInfoSuccess(sender, args) {
lblData.html(
'Title: ' + web.get_title() + '<br/>' +
'Description: ' + web.get_description()
);
}
function getHostInfoError(sender, args) {
lblData.html(
'Request Failed: ' + args.get_message() + '\n' +
'Stacktrace: ' + args.get_stackTrace()
);
}
}
}

Related

Changing image based on location data output

I am trying to show/echo users location on a webpage using maxmind geoip2 paid plan, I also want to show different images based on the state/city names output.
For example, if my webpage shows the user is from New York, I would like to show a simple picture of New York, if the script detects the user is from Washington, the image should load for Washington.
This is the snippet I have tried but doesn't work.
<script type="text/javascript">
if
$('span#region=("New York")') {
// Display your image for New York
document.write("<img src='./images/NY.jpg'>");
}
else {
document.write("<img src='./images/different.jpg'>");
}
</script>
This is the code in the header.
<script src="https://js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>
<script>
var onSuccess = function(geoipResponse) {
var cityElement = document.getElementById('city');
if (cityElement) {
cityElement.textContent = geoipResponse.city.names.en || 'Unknown city';
}
var countryElement = document.getElementById('country');
if (countryElement) {
countryElement.textContent = geoipResponse.country.names.en || 'Unknown country';
}
var regionElement = document.getElementById('region');
if (regionElement) {
regionElement.textContent = geoipResponse.most_specific_subdivision.names.en || 'Unknown region';
}
};
var onError = function(error) {
window.console.log("something went wrong: " + error.error)
};
var onLoad = function() {
geoip2.city(onSuccess, onError);
};
// Run the lookup when the document is loaded and parsed. You could
// also use something like $(document).ready(onLoad) if you use jQuery.
document.addEventListener('DOMContentLoaded', onLoad);
</script>
And this simple span shows the state name in body text of the Html when the page loads.
<span id="region"></span>
now the only issue is the image doesn't change based on users location, what am i doing wrong here?
Your example is missing some code, but it looks like you are running some code immediately and some code in a callback, a better way to do it is to have all the code in the callback:
// whitelist of valid image names
var validImages = ["NJ", "NY"];
// get the main image you want to replace
var mainImage = document.getElementById('mainImage');
if (mainImage) {
// ensure there is a subdivision detected, or load the default
if(geoipResponse.subdivisions[0].iso_code && validImages.includes( && geoipResponse.subdivisions[0].iso_code)){
mainImage.src = "./images/" + geoipResponse.subdivisions[0].iso_code + ".jpg";
} else {
mainImage.src = "./images/different.jpg";
}
}
Then just have the image you want to replace be:
<img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D" id="mainImage" />
Notes:
If you are using a responsive image, make sure your transparent gif is the same ratio height of to width as your final image to avoid page reflows.
You will have to load the different.jpg in the onError callback as well.

How to search for a file in a document set?

I'm trying to write a CAML query to look for a specific file, by file name, in a specific document set.
This is the query I'm working on:
<Query>
<Where>
<Eq>
<FieldRef Name='FileLeafRef' />
<Value Type='File'>TestFile.txt</Value>
</Eq>
</Where>
</Query>
<QueryOptions>
<Folder>https://acme.com/sites/mysite/MyDocLib/MyDocSetName</Folder>
</QueryOptions>
As there is a file called TestFile.txt in a document set called MyDocSetName, I expect to get a result, but nothing is coming back. What am I doing wrong?
Sample tested script based on this demo.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.Runtime.js", function() {
$.getScript(scriptbase + "SP.js", function() {
$.getScript(scriptbase + "SP.DocumentManagement.js", createDocumentSet);
});
});
});
var docSetFiles;
function createDocumentSet() {
//Get the client context,web and library object.
clientContext = new SP.ClientContext.get_current();
oWeb = clientContext.get_web();
var oList = oWeb.get_lists().getByTitle("DocSet");
clientContext.load(oList);
//Get the root folder of the library
oLibraryFolder = oList.get_rootFolder();
var documentSetFolder = "/DocSet/test1";
//Get the document set files using CAML query
var camlQuery = SP.CamlQuery.createAllItemsQuery();
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>test2.docx</Value></Eq></Where></Query></View>");
camlQuery.set_folderServerRelativeUrl(documentSetFolder);
docSetFiles = oList.getItems(camlQuery);
//Load the client context and execute the batch
clientContext.load(docSetFiles, 'Include(File)');
clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
}
function QuerySuccess() {
//Loop through the document set files and get the display name
var docSetFilesEnumerator = docSetFiles.getEnumerator();
while (docSetFilesEnumerator.moveNext()) {
var oDoc = docSetFilesEnumerator.get_current().get_file();
console.log("Document Name : " + oDoc.get_name());
}
}
function QueryFailure() {
console.log('Request failed - ' + args.get_message());
}
</script>

Holoview chart won't appear in Django site

i know there is probably something simple i am doing wrong, but i don't know where else to get an answer. I created a django site and the following function returns holoview html:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from charts.models import Ord
from IPython.display import display_html
import pandas as pd
import holoviews as hv
hv.extension('bokeh')
renderer = hv.renderer('bokeh')
# Create your views here.
def displayChart(request):
df = pd.DataFrame(list(Ord.objects.using('DB').all().values('ordtyp')[:500]))
df = df.groupby([df.ordtyp]).size().reset_index(name='counts')
bars = hv.Bars(df, kdims=[('ordtyp', 'Order Type')], vdims=[('counts', 'Count of Orders')])
hv.Store.registry['bokeh'][hv.Bars]
html = renderer.html(bars)
return render(request, 'charts/charts.html', {'html': html})
i put a block in the charts.html file as:
{{ html |safe }}
and all i get is a blank page. i then took the raw html that the renderer is returning and tried to copy and paste it directly into my html file, and got the same thing. the html is below. Also, the chart does work in Jupyter Notebook... can you tell me what i am doing wrong?
charts.html:
> <!DOCTYPE html>
> <html>
> <head>
> <title>Charts</title>
> </head>
> <body>
> {{html|safe}}
> </body>
> </html>
raw html that the renderer returned:
<div style='display: table; margin: 0 auto;'>
<div class="bk-root">
<div class="bk-plotdiv" id="0dd69ef6-4d30-48f5-a95a-1201437920de"></div>
</div>
<script type="text/javascript">
(function(root) {
function now() {
return new Date();
}
var force = false;
if (typeof (root._bokeh_onload_callbacks) === "undefined" || force === true) {
root._bokeh_onload_callbacks = [];
root._bokeh_is_loading = undefined;
}
if (typeof (root._bokeh_timeout) === "undefined" || force === true) {
root._bokeh_timeout = Date.now() + 0;
root._bokeh_failed_load = false;
}
var NB_LOAD_WARNING = {'data': {'text/html':
"<div style='background-color: #fdd'>\n"+
"<p>\n"+
"BokehJS does not appear to have successfully loaded. If loading BokehJS from CDN, this \n"+
"may be due to a slow or bad network connection. Possible fixes:\n"+
"</p>\n"+
"<ul>\n"+
"<li>re-rerun `output_notebook()` to attempt to load from CDN again, or</li>\n"+
"<li>use INLINE resources instead, as so:</li>\n"+
"</ul>\n"+
"<code>\n"+
"from bokeh.resources import INLINE\n"+
"output_notebook(resources=INLINE)\n"+
"</code>\n"+
"</div>"}};
function display_loaded() {
if (root.Bokeh !== undefined) {
var el = document.getElementById("0dd69ef6-4d30-48f5-a95a-1201437920de");
if (el != null) {
el.textContent = "BokehJS " + Bokeh.version + " successfully loaded.";
}
} else if (Date.now() < root._bokeh_timeout) {
setTimeout(display_loaded, 100)
}
}
function run_callbacks() {
try {
root._bokeh_onload_callbacks.forEach(function(callback) { callback() });
}
finally {
delete root._bokeh_onload_callbacks
}
console.info("Bokeh: all callbacks have finished");
}
function load_libs(js_urls, callback) {
root._bokeh_onload_callbacks.push(callback);
if (root._bokeh_is_loading > 0) {
console.log("Bokeh: BokehJS is being loaded, scheduling callback at", now());
return null;
}
if (js_urls == null || js_urls.length === 0) {
run_callbacks();
return null;
}
console.log("Bokeh: BokehJS not loaded, scheduling load and callback at", now());
root._bokeh_is_loading = js_urls.length;
for (var i = 0; i < js_urls.length; i++) {
var url = js_urls[i];
var s = document.createElement('script');
s.src = url;
s.async = false;
s.onreadystatechange = s.onload = function() {
root._bokeh_is_loading--;
if (root._bokeh_is_loading === 0) {
console.log("Bokeh: all BokehJS libraries loaded");
run_callbacks()
}
};
s.onerror = function() {
console.warn("failed to load library " + url);
};
console.log("Bokeh: injecting script tag for BokehJS library: ", url);
document.getElementsByTagName("head")[0].appendChild(s);
}
};var element = document.getElementById("0dd69ef6-4d30-48f5-a95a-1201437920de");
if (element == null) {
console.log("Bokeh: ERROR: autoload.js configured with elementid '0dd69ef6-4d30-48f5-a95a-1201437920de' but no matching script tag was found. ")
return false;
}
var js_urls = [];
var inline_js = [
function(Bokeh) {
(function() {
var fn = function() {
var docs_json = {"c7d02456-4a61-46d2-8431-34face1e6c67":{"roots":{"references":[{"attributes":{"callback":null,"column_names":["ORDTYP","counts"],"data":{"ORDTYP":["CC","CD","CZ","DB","DR","ED","EI","IC","ID","IP","MC","MF","MI","MK","MP","MS","MX","PC","PM","PT","SD","TI","TX","ZLR"],"counts":[60,3,2,17,1,13,2,28,21,1,3,6,1,2,2,35,10,20,12,2,525,7,225,1]}},"id":"46c2f30a-31d4-4c3f-ade2-4de96e13a4db","type":"ColumnDataSource"},{"attributes":{"active_drag":"auto","active_inspect":"auto","active_scroll":"auto","active_tap":"auto","tools":[{"id":"16eb22e8-c448-49d7-ab20-a02f2ebb3e5c","type":"SaveTool"},{"id":"218dbf74-8190-491c-b2dc-d13097c1f9e4","type":"PanTool"},{"id":"03f67199-1622-4784-b9a2-b36b4a47477b","type":"WheelZoomTool"},{"id":"d48948b1-297b-4915-bf84-916a417b01ee","type":"BoxZoomTool"},{"id":"722ae387-76c5-48cb-a387-7090de91b014","type":"ResetTool"}]},"id":"8ce67c3d-e8dc-41a2-86a8-76685fb90fe9","type":"Toolbar"},{"attributes":{"callback":null,"end":525,"start":0},"id":"16f5dfe6-08a6-4ad8-a190-bdf67979b26c","type":"DataRange1d"},{"attributes":{},"id":"bfe7ff64-0995-43a7-8944-6d491bf93b14","type":"CategoricalTicker"},{"attributes":{"callback":null,"factors":["CC","CD","CZ","DB","DR","ED","EI","IC","ID","IP","MC","MF","MI","MK","MP","MS","MX","PC","PM","PT","SD","TI","TX","ZLR"]},"id":"36f2f454-71a9-4511-a446-2c56a015ecd0","type":"FactorRange"},{"attributes":{"axis_label":"Count of Orders","formatter":{"id":"7303c9ca-b3e1-40be-bd44-1ef7f06d8a2d","type":"BasicTickFormatter"},"plot":{"id":"c84e964a-0b0b-4d95-aa2c-3657b7811bd0","subtype":"Figure","type":"Plot"},"ticker":{"id":"95b801e5-1f32-4ff1-be0c-e64ddcb14fa3","type":"BasicTicker"}},"id":"bd1e5045-1d72-4e92-8914-13be1ee0d04f","type":"LinearAxis"},{"attributes":{},"id":"95b801e5-1f32-4ff1-be0c-e64ddcb14fa3","type":"BasicTicker"},{"attributes":{"grid_line_color":{"value":null},"plot":{"id":"c84e964a-0b0b-4d95-aa2c-3657b7811bd0","subtype":"Figure","type":"Plot"},"ticker":{"id":"bfe7ff64-0995-43a7-8944-6d491bf93b14","type":"CategoricalTicker"}},"id":"0dee56d3-b965-4d15-bf6d-93cd1ea2a20d","type":"Grid"},{"attributes":{"bottom_units":"screen","fill_alpha":{"value":0.5},"fill_color":{"value":"lightgrey"},"left_units":"screen","level":"overlay","line_alpha":{"value":1.0},"line_color":{"value":"black"},"line_dash":[4,4],"line_width":{"value":2},"plot":null,"render_mode":"css","right_units":"screen","top_units":"screen"},"id":"2a376fc3-0bcc-47df-a0e8-2389040d3254","type":"BoxAnnotation"},{"attributes":{"plot":null,"text":"","text_color":{"value":"black"},"text_font_size":{"value":"12pt"}},"id":"04310042-3ae0-4955-bd48-3d9c8e2d9be2","type":"Title"},{"attributes":{},"id":"722ae387-76c5-48cb-a387-7090de91b014","type":"ResetTool"},{"attributes":{"dimension":1,"grid_line_color":{"value":null},"plot":{"id":"c84e964a-0b0b-4d95-aa2c-3657b7811bd0","subtype":"Figure","type":"Plot"},"ticker":{"id":"95b801e5-1f32-4ff1-be0c-e64ddcb14fa3","type":"BasicTicker"}},"id":"a281b265-486f-42a3-829a-c71bfd6830d0","type":"Grid"},{"attributes":{"axis_label":"Order Type","formatter":{"id":"259e4d35-20fb-4eb4-9fbd-6068fef93c0d","type":"CategoricalTickFormatter"},"plot":{"id":"c84e964a-0b0b-4d95-aa2c-3657b7811bd0","subtype":"Figure","type":"Plot"},"ticker":{"id":"bfe7ff64-0995-43a7-8944-6d491bf93b14","type":"CategoricalTicker"}},"id":"9f673b5b-85bf-40d1-96f3-b27737ecc242","type":"CategoricalAxis"},{"attributes":{},"id":"218dbf74-8190-491c-b2dc-d13097c1f9e4","type":"PanTool"},{"attributes":{},"id":"259e4d35-20fb-4eb4-9fbd-6068fef93c0d","type":"CategoricalTickFormatter"},{"attributes":{},"id":"16eb22e8-c448-49d7-ab20-a02f2ebb3e5c","type":"SaveTool"},{"attributes":{},"id":"721998c2-dee0-4e47-9a6d-ecef76d53889","type":"LinearScale"},{"attributes":{},"id":"03f67199-1622-4784-b9a2-b36b4a47477b","type":"WheelZoomTool"},{"attributes":{"overlay":{"id":"2a376fc3-0bcc-47df-a0e8-2389040d3254","type":"BoxAnnotation"}},"id":"d48948b1-297b-4915-bf84-916a417b01ee","type":"BoxZoomTool"},{"attributes":{"data_source":{"id":"46c2f30a-31d4-4c3f-ade2-4de96e13a4db","type":"ColumnDataSource"},"glyph":{"id":"3ab94627-160a-4913-95e6-c25fa17a1d51","type":"VBar"},"hover_glyph":null,"muted_glyph":null,"nonselection_glyph":{"id":"f72f6dc1-7c71-4f5e-80f9-fbd1351268b3","type":"VBar"},"selection_glyph":null,"view":{"id":"9df174a0-4967-47fd-82f3-3d054eee1a12","type":"CDSView"}},"id":"897248ec-4fbd-404c-b3b3-09900b6e3560","type":"GlyphRenderer"},{"attributes":{"fill_alpha":{"value":0.1},"fill_color":{"value":"#30a2da"},"line_alpha":{"value":0.1},"line_color":{"value":"#000000"},"top":{"field":"counts"},"width":{"value":0.8},"x":{"field":"ORDTYP"}},"id":"f72f6dc1-7c71-4f5e-80f9-fbd1351268b3","type":"VBar"},{"attributes":{"fill_color":{"value":"#30a2da"},"line_color":{"value":"#000000"},"top":{"field":"counts"},"width":{"value":0.8},"x":{"field":"ORDTYP"}},"id":"3ab94627-160a-4913-95e6-c25fa17a1d51","type":"VBar"},{"attributes":{"source":{"id":"46c2f30a-31d4-4c3f-ade2-4de96e13a4db","type":"ColumnDataSource"}},"id":"9df174a0-4967-47fd-82f3-3d054eee1a12","type":"CDSView"},{"attributes":{},"id":"eb1872c1-4fa5-47b0-b5c7-43dfe9b890e3","type":"CategoricalScale"},{"attributes":{},"id":"7303c9ca-b3e1-40be-bd44-1ef7f06d8a2d","type":"BasicTickFormatter"},{"attributes":{"background_fill_color":{"value":"white"},"below":[{"id":"9f673b5b-85bf-40d1-96f3-b27737ecc242","type":"CategoricalAxis"}],"left":[{"id":"bd1e5045-1d72-4e92-8914-13be1ee0d04f","type":"LinearAxis"}],"min_border_bottom":10,"min_border_left":10,"min_border_right":10,"min_border_top":10,"plot_height":300,"plot_width":300,"renderers":[{"id":"9f673b5b-85bf-40d1-96f3-b27737ecc242","type":"CategoricalAxis"},{"id":"0dee56d3-b965-4d15-bf6d-93cd1ea2a20d","type":"Grid"},{"id":"bd1e5045-1d72-4e92-8914-13be1ee0d04f","type":"LinearAxis"},{"id":"a281b265-486f-42a3-829a-c71bfd6830d0","type":"Grid"},{"id":"2a376fc3-0bcc-47df-a0e8-2389040d3254","type":"BoxAnnotation"},{"id":"897248ec-4fbd-404c-b3b3-09900b6e3560","type":"GlyphRenderer"}],"title":{"id":"04310042-3ae0-4955-bd48-3d9c8e2d9be2","type":"Title"},"toolbar":{"id":"8ce67c3d-e8dc-41a2-86a8-76685fb90fe9","type":"Toolbar"},"x_range":{"id":"36f2f454-71a9-4511-a446-2c56a015ecd0","type":"FactorRange"},"x_scale":{"id":"eb1872c1-4fa5-47b0-b5c7-43dfe9b890e3","type":"CategoricalScale"},"y_range":{"id":"16f5dfe6-08a6-4ad8-a190-bdf67979b26c","type":"DataRange1d"},"y_scale":{"id":"721998c2-dee0-4e47-9a6d-ecef76d53889","type":"LinearScale"}},"id":"c84e964a-0b0b-4d95-aa2c-3657b7811bd0","subtype":"Figure","type":"Plot"}],"root_ids":["c84e964a-0b0b-4d95-aa2c-3657b7811bd0"]},"title":"Bokeh Application","version":"0.12.7"}};
var render_items = [{"docid":"c7d02456-4a61-46d2-8431-34face1e6c67","elementid":"0dd69ef6-4d30-48f5-a95a-1201437920de","modelid":"c84e964a-0b0b-4d95-aa2c-3657b7811bd0"}];
Bokeh.embed.embed_items(docs_json, render_items);
};
if (document.readyState != "loading") fn();
else document.addEventListener("DOMContentLoaded", fn);
})();
},
function(Bokeh) {
}
];
function run_inline_js() {
if ((root.Bokeh !== undefined) || (force === true)) {
for (var i = 0; i < inline_js.length; i++) {
inline_js[i].call(root, root.Bokeh);
}if (force === true) {
display_loaded();
}} else if (Date.now() < root._bokeh_timeout) {
setTimeout(run_inline_js, 100);
} else if (!root._bokeh_failed_load) {
console.log("Bokeh: BokehJS failed to load within specified timeout.");
root._bokeh_failed_load = true;
} else if (force !== true) {
var cell = $(document.getElementById("0dd69ef6-4d30-48f5-a95a-1201437920de")).parents('.cell').data().cell;
cell.output_area.append_execute_result(NB_LOAD_WARNING)
}
}
if (root._bokeh_is_loading === 0) {
console.log("Bokeh: BokehJS loaded, going straight to plotting");
run_inline_js();
} else {
load_libs(js_urls, function() {
console.log("Bokeh: BokehJS plotting callback run at", now());
run_inline_js();
});
}
}(window));
</script></div>
THANKS!
You are missing the JS and CSS that's required to render this output. You can either manually include BokehJS as a script tag, e.g. for bokeh 0.12.9 you'd add this:
<link
href="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.9.min.css"
rel="stylesheet" type="text/css">
<link
href="http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.9.min.css"
rel="stylesheet" type="text/css">
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.9.min.js"></script>
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.6.min.js"></script>
Alternatively you can also use the renderer.static_html method to export a div which includes all the required JS and CSS, e.g.:
hmap = hv.HoloMap({i: hv.Curve(np.random.rand(10)*i) for i in range(1,5)})
html = hv.renderer('bokeh').static_html(hmap)
with open('test.html', 'w') as f:
f.write(html)
The static_html method also accepts a template to embed the JS, CSS and HTML separately:
<html>
<head>
{css}
{js}
</head>
<body>
{html}
</body>
</html>
In future releases we will also have a components method letting you get the JS, CSS and HTML components separately.

Django-disqus: disqus comment box on

I've created a blog with django and am trying to use disqus comments. I am having a similar problem that I have seen in other questions in that when I post comments to any entries(on single entry pages) they all show up on the main page under one entry.
The main problem is that on the main page of the blog, where I have multiple entries, I can only get one disqus comment box to show up on one entry. When I look at the source code the javascript variables for the other blog entries seem to be showing up correctly so I'm not sure why the comment boxes won't render under the other blog entries.
I'm in development mode so I'm not sure if that makes a difference...I'm also a noob at all of this.
This is the source code I get for the disqus javascript for each entry...can anyone help me figure out why I can't get the comment box to render?
<div id="disqus_thread"></div>
<script type="text/javascript">
/* <![CDATA[ */
var disqus_shortname = 'whometaxi';
var disqus_developer = "1";
var disqus_identifier = "3";
var disqus_title = "Third";
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<div id="disqus_thread"></div>
<script type="text/javascript">
/* <![CDATA[ */
var disqus_shortname = 'whometaxi';
var disqus_developer = "1";
var disqus_identifier = "1";
var disqus_title = "First post";
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<script type="text/javascript">
/* <![CDATA[ */
var disqus_shortname = 'whometaxi';
var disqus_developer = "1";
var disqus_identifier = "2";
var disqus_title = "Second!";
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
Disqus is designed to load one Disqus postbox per page. Disqus uses the page URL as a unique identifier and only one Disqus embed can be associated with a single URL. If more than one Disqus embed is present in the source code of a page, only one embed will load.
There is a way to reload the disqus embed with different identifiers:
DISQUS.reset({
reload: true,
config: function () {
this.page.identifier = "newidentifier";
this.page.url = "http://example.com/#!newthread";
}
});
However, this method is still only used with one embed per page.
This is solved but I'd like to show a different approach by using django-disqus. The last line is the one that gets you the right comments for the specific page/object.
Install django-disqus and use it in your templates.
pip install django-disqus
Add disqus to your INSTALLED_APPS and put your disqus api key in your settings:
settings.py
INSTALLED_APPS = (
...
'disqus',
...
)
DISQUS_API_KEY = 'YOUR_SECRET_API_KEY'
DISQUS_WEBSITE_SHORTNAME = 'YOUR_WEBSITE_SHORTNAME'
Use disqus template tags in your templates:
some_template.html
# load the tags
{% load disqus_tags %}
# get comments for your website
{% disqus_show_comments "YOUR_WEBSITE_SHORTNAME" %}
# get the url for the current object to get the right comments
{% set_disqus_url object.get_absolute_url %}

Load PHP file with document.createElement()

How could I make this work? I want to load a php file like this:
Click button.
Call Javascript function.
In Javascript function create an img with src file.php.
This should force the loading of the php. Here is the code.
<script type="text/javascript">
var d;
function callSave() {
alert ('calling');
if (d) document.body.removeChild(d);
// d = document.createElement("script");
d = document.createElement("img");
d.src = "savepages.php";
//d.type = "text/javascript";
document.body.appendChild(d);
}
</script>
Then in savepages.php I do another alert to verify that the php is called and it isn't. Here is the savepages.php.
<?php
echo "alert('from the php');";
?>
The alert from the php doesn't happen. Is there a different element type that will force loading of the php? I don't have ajax installed, so I need a workaround like this.
Thanks.
You could use an iframe element
<script type="text/javascript">
var d;
function callSave() {
alert ('calling');
if (d) document.body.removeChild(d);
d = document.createElement("iframe");
d.src = "savepages.php";
document.body.appendChild(d);
}
</script>
Found out the better way to handle this. There is this simple code that explains how to call a javascript function from a form event and from that javascript function load a PHP file. The code found at http://daniel.lorch.cc/docs/ajax_simple/ is also given here:
<script type="text/javascript">
var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
function validate(user) {
http.abort();
http.open("GET", "validate.php?name=" + user, true);
http.onreadystatechange=function() {
if(http.readyState == 4) {
document.getElementById('msg').innerHTML = http.responseText;
}
}
http.send(null);
}
</script>
<h1>Please choose your username:</h1>
<form>
<input type="text" onkeyup="validate(this.value)" />
<div id="msg"></div>
</form>
validate.php
<?php
function validate($name) {
if($name == '') {
return '';
}
if(strlen($name) < 3) {
return "<span id=\"warn\">Username too short</span>\n";
}
switch($name) {
case 'bob':
case 'jim':
case 'joe':
case 'carol':
return "<span id=\"warn\">Username already taken</span>\n";
}
return "<span id=\"notice\">Username ok!</span>\n";
}
echo validate(trim($_REQUEST['name']));
?>