Load PHP file with document.createElement() - src

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']));
?>

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.

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.

Retrieve data from list in SharePoint 2013 provider hosted App

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

angularjs not responding the GET method

i am relatively new in django and angualarJs.The problem is that angularJs is not responding the get method properly.I have a webpage developed by django where i have a search field.For the execution of search i use a angularJs functionality that is ng-submit and write angularJs code to return value using get method.May be i made a mistake here.you can see my code... here is my template which containing the angularJs also...
<div class="navbar navbar-default " ng-controller="NavCtrl">
<form action="" class="navbar-form navbar-right" ng-submit="search()">
<input class="form-control col-lg-8" type="text" placeholder="Search" ng-model="term"></input>
</form>
</div>
<script>
app.controller("NavCtrl", ['$scope', '$http', '$location', '$q', '$timeout',
function NavCtrl($scope, $http, $location, $q, $timeout) {
$scope.results = ["Test"];
$scope.term = "";
$scope.reqs = "5";
$scope.pics = "45";
$scope.ddata = "asdasd";
$scope.ddata = $http.post("{% url 'get-nav-info' %}").success(
function (result) {
//$scope.reqs = result.data.data.num_request;
//$scope.pics = result.data.data.num_photo;
return result.data;
}
);
//$scope.reqs = $scope.ddata.num_request;
//$scope.pics = $scope.ddata.num_photo;
$scope.search = function () {
//alert("test");
//$location.absUrl("{% url 'search-term-show' %}").search({'term':$scope.term}).apply();
//$location.path("{% url 'search-term-show' %}").search({'term':$scope.term}).apply();
$http.get("{% url 'search-term-show' %}?term=" + $scope.term).success(function (result) {
return result.data;
});
//$scope.$apply();
}
}
]);
</script>
now the problem is that while i press enter ,there is no result,but if i manually write this URL which is http://www.kothay.com/searchphoto/?term=a in the address bar then the result is showing .In mention,this url is the that url which should be appear in the address bar when i press the enter to search my photos.But with the enter press its not appearing in the address bar and that's why the results are not showing.I hope you can understand what i am trying to say.May be there is a mistake in my code.Please help me to fix this problem.
You are doing thing wrong.
1st, the success is a defer of get, so return result.data and returns it to the get deferred and there it goes to the heaven. So if you would like to keep the current architecture it should look more like this
$scope.search = [];
getsearch = function () {
$http.get("{% url 'search-term-show' %}?term=" + $scope.term).success(function (result) {
$scope.search = result.data;
});
};
getsearch();
2nd that can still not update your UI cuz if the ctrl function is over and the digest is over before your response it wont update your UI cuz its in another scope (not $scope, but the programmatically term scope). The solution to this is to put your data in a service and in your ctr just do.
function ctrl($scope, myservice){
$scope.data = myservice;
}
ng-repeat="x in data.results"
Here is a full tutorial http://bresleveloper.blogspot.co.il/2013/08/breslevelopers-angularjs-tutorial.html
And last thing its just a good practice to always have .error(...)

SWFobject embedded swf, ExternalInterface.Call returns null

im working on a flash game with django backend using swfobject to embed the swf into the view,
however when i do externalinterface.call() from flash in InternetExplorer(Chrome and Firefox are fine), it returns null
the flash game itself works perfectly
Django view and embed code:
<div id="game_container">
<div id='flashContent'></div>
</div>
<script type="text/javascript" src="swfobject.js"></script>
<script type='text/javascript'>
var flashvars={{flashvars|safe}};
var params={wmode:"opaque", allowscriptaccess:"always" };
var attributes={id:"flashContent", name:"flashContent"};
swfobject.embedSWF("{{SWF_URL}}", "flashContent", "{{ appsettings.SWF_WIDTH }}", "{{ appsettings.SWF_HEIGHT }}", "10.0.0", false, flashvars, params, attributes);
</script>
function fqlearn_isEventInteresting(data) {
ln_log(['isEventInteresting',data]);
if (!BASE_URL) BASE_URL = data.baseURL;
ln_log(['got lesson?',fqlearn_findLearningModule(data) != null]);
return fqlearn_findLearningModule(data) != null;
//shuld return either true or false.
}
Flash AS3 code:
var isInteresting:Object = false;
try {
isInteresting = ExternalInterface.call('fqlearn_isEventInteresting', data);
} catch (e:Error) {
trace("error calling external interface");
// Container does not support outgoing calls :/
rpc.forceLogUncaughtError("ExternalInterface.call problem",
e.name, e.toString(), e.getStackTrace());
rest.apply(restThis);
return;
} catch (e:SecurityError) {
// Security sandbox nonsense :/
throw e;
}
if (isInteresting == null) {
// Something went wrong :/
rpc.forceLogUncaughtError("ExternalInterface.call problem", "JS_returned_null_error");
}
if (isInteresting) {
trace("showing learning blackout")
dispatch(CoordinationEvent.newLEARNING_ABOUT_TO_SHOW());
learningPendingData = {
rest: rest,
restThis: restThis
};
ExternalInterface.call() from Flash in InternetExplorer(Chrome and Firefox are fine), it returns null . how do i fix this?
Fixed it: console.debug was choking up Internet Explorer. I removed those and it worked.