Can anyone fill me in as to why this isn't pulling my JSON data. I think I have the syntax correct but the page doesn't pull the data. Any thoughts?
<!DOCTYPE html>
<html>
<head>
<title>PhoneGap Ajax Sample</title>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript">
function appReady(){
var ajax = new XMLHttpRequest();
ajax.open("GET","http://www.lcbcchurch.com/mobileJSON/homeslideshow",true);
ajax.send();
ajax.onreadystatechange=function(){
if(ajax.readyState==4 && (ajax.status==200||ajax.status==0)){
eval('var data = ' + ajax.responseText + ';');
var theResults = data.results;
var theHTML = '';
for(var i=0;i<theResults.length;i++){
theHTML += [
'<div class="avatar"> <img src='+theResults[i].slideshow-image+' />'].join('');
}
document.getElementById('main').innerHTML = theHTML;
}
}
}
document.addEventListener("deviceready", appReady, false);
</script>
</head>
<body>
<div id="main">
</div>
</body>
</html>
Hard to tell without additional information, but:
Set ajax.onreadystatechange before you call .send() otherwise the response could, in theory, arrive before you've told the instance how to handle it - it would be entirely dependent on the browser implementation.
Secondly, are you hosting it, or trying it locally from your filesystem? In many browsers, Ajax calls don't work from the filesystem (it is considered a cross site scripting vulnerability) - so its best to install a simple webserver locally to test on - and fetch the json from that too.
Lastly, don't use eval, its evil ;-)
Use
var result = JSON.parse(string);
instead.
Related
I need to build a cross platform app with multiple windows. So I would like to know how to use html templates in electron.
Based on a similar question and what I've seen, there's no built in html template language in Electron, which is actually great because it allows you to use any other template language.
I'm currently playing with ejs in Electron.
Below is my index.ejs template file:
<html lang="en">
<head>
<title>The Index Page</title>
</head>
<body>
<h1>Welcome, this is the Index page.</h1>
<% if (user) { %>
<h3>Hello there <%= user.name %></h3>
<% } %>
</body>
</html>
And below is a section of my main.js file where the above template is rendered and loaded onto the BrowserWindow. Note that I've left out most of the boilerplate code:
const ejs = require('ejs');
//... Other code
let win = new BrowserWindow({width: 800, height: 600});
//... Other code
// send the data and options to the ejs template
let data = {user: {name: "Jeff"}};
let options = {root: __dirname};
ejs.renderFile('index.ejs', data, options, function (err, str) {
if (err) {
console.log(err);
}
// Load the rendered HTML to the BrowserWindow.
win.loadURL('data:text/html;charset=utf-8,' + encodeURI(str));
});
I'll give some credit to this gist for helping me find the data:text/html;charset=utf-8 part of the url that can be used to load dynamic content.
UPDATE
I'm actually not using this anymore. It's faster to just load the default html and use the native DOM methods. The Electron Quickstart program shows how to do this nicely.
Another option is to do the templating during your build. Here is a simple example using gulp to add nonces to the CSP meta tag and the inline script.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'nonce-<%= scriptNonce %>';">
<title>Basic Electron App</title>
</head>
<body>
<div id="app"></div>
<script type="application/javascript" nonce=<%= scriptNonce %>>
require('./index.js');
</script>
</body>
</html>
and in gulfile.js add the following to what you already have and make sure this task is included in your pipeline. You can also just update your current html task with the code below.
const template = require('gulp-template');
const uuidv4 = require('uuid/v4');
gulp.task('copy-html', () => {
// Create nonces during the build and pass them to the template for use with inline scripts and styles
const nonceData = {
scriptNonce: new Buffer(uuidv4()).toString('base64'),
styleNonce: new Buffer(uuidv4()).toString('base64')
};
return gulp.src('src/*.html')
.pipe(template(nonceData))
.pipe(gulp.dest('dist/'));
});
This is a very stripped down example. I have a more complete example at https://github.com/NFabrizio/data-entry-electron-app if anyone is interested, though there is still one warning when running the application because one of the packages I am using pulls in react-beautiful-dnd, which adds inline styles but does not currently accept nonces.
I have problem with mobile/tablet version of page which I create
I need this: When someone look at product detail and move him to right/left (touch/swipe) then I need load next/previous product detail (= Example: Now I on page with id=2 when I go right, then I load page with id=3, npw I on page with id=3 and I go left then I load page with id=2.. etc.. with different pages id).
I look in thread here, but this solution is not dynamic and I have problem applicate it. Next I inspirated in W3C here.
Now I have these codes which not work:
JS file:
$(document).on('pageinit', function() {
$('.epicFullscreen').bind('swipeleft', function(event,ui)
{
$.mobile.changePage("http://www.some_domain.cz/category/page_name-1/","slide");
});
$('.epicFullscreen').bind('swiperight', function()
{
$.mobile.changePage("http://www.some_domain.cz/category/page_name-3/","slide");
});
});
$(document).on('pagehide', function () { $(this).off('swipeleft swiperight'); });
HTML:
<script src="funkce/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="funkce/jquery.mobile-1.3.2.min.js" type="text/javascript"></script>
<script src="funkce/skripty.js" type="text/javascript"></script>
I need use old JQuery 1.7.1. because this site using it and everything works fine, with newer JQuery I can have new problems. For that I use older JQuery-mobile 1.3.2. which must work with JQuery 1.7.1. ("jQuery Mobile 1.3 supports jQuery 1.7 and newer") . I can´t include "jquery.mobile-1.3.2.min.css" because this styles not work together with my styles correctly.
HTML in body is like that:
<div class="epicFullscreen">
<img class="epicImg" src="../../data_9/11normal.jpg" alt="inspirace č.2" title="inspirace č.2" border="0" />
</div>
Now I have dynamic solution with arrows (right/left) and with adding correct urls with PHP, but on tablet/mobile user like using touch not clicking on arrows etc...
=> Where I have problem and why not work my current solution? And how I can change this static JS to dynamic JS?
try this simple code .....
$(document).on("swipeleft", '#'+event.target.id, function () {
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
alert(nextpage.attr('id'));
$.mobile.changePage(nextpage, "slide", false, true);
}
});
$(document).on("swiperight", '#'+event.target.id, function () {
var prevpage = $(this).prev('div[data-role="page"]');
if (prevpage.length > 0) {
$.mobile.changePage(prevpage, { transition: "slide", reverse: true }, true, true);
}
});
I found solution for that I make this answer. I simplify my problem and create simple page.
Code
<!DOCTYPE html>
<html>
<head>
<!--<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">-->
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="jquery.mobile-1.3.2.min.js" type="text/javascript"></script>
<script>
$(document).on("pageinit",function(){
var pathname = $(location).attr('href');
var leva = $('#le').attr("href");
var prava = $('#pr').attr("href");
$("body").on("swiperight",function(){
<!--alert("You swiped right!");-->
location.href=prava;
});
$("body").on("swipeleft",function(){
<!--alert("You swiped left!");-->
location.href=leva;
});
});
</script>
</head>
<body>
<div id="test_div" style="display: block;">
<img src="test.gif" width="100px">
<a id="le" href="http://www.some_domain.cz/category/page_name-1/">left</a>
<a id="pr" href="http://www.some_domain.cz/category/page_name-3/">right</a>
</div>
</body>
</html>
I have this one hack - in PHP I know on which page I am, which page is before and which is next, I add this links it to arrows (which have tag "a"). This function working perfect. But I use this functional code to get correct URL => I don´t need some big function in JQuery which can split actual url with RegEx, know on which page I am, know if exist next page etc... Now I must only style this code to my page, but this is working.
I thank Omar for his time and I close this topic.
I am making a website for a hotel. And the contact/booking form should contain a text field so that the user can write his/her country/city of origin.
I would like to implement a kind of geotracking, geolocalization or something that allow me to get the country/city of origin and use that information in a form's field so that the field's contents will be delivered with the rest of the information via email.
I have tried the code as in this website http://www.maestrosdelweb.com/util/geo/geo.html, whose code I place here:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head><script type="text/javascript">
//<![CDATA[
try{if (!window.CloudFlare) { var CloudFlare=[{verbose:0,p:0,byc:0,owlid:"cf",mirage:{responsive:0,lazy:0},oracle:"35/0f710f6add20ad3fc449c08c96bdf2",paths:{cloudflare:"/cdn-cgi/nexp/aav=366183412/"},atok:"3ef00aeff8d6c935da4e270822a8471b",zone:"maestrosdelweb.com",rocket:"0",apps:{"ga_key":{"ua":"UA-309831-1","ga_bs":"2"}}}];var a=document.createElement("script"),b=document.getElementsByTagName("script")[0];a.async=!0;a.src="//ajax.cloudflare.com/cdn-cgi/nexp/aav=4114775854/cloudflare.min.js";b.parentNode.insertBefore(a,b);}}catch(e){};
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
window.__CF=window.__CF||{};window.__CF.AJS={"ga_key":{"ua":"UA-309831-1","ga_bs":"2"}};
//]]>
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="robots" content="noindex,follow"/>
<title>Geolocalizacion con HTML5</title>
<link rel="shortcut icon" href="/favicon.ico"/>
<style type="text/css">img{border:0}</style>
<script type="text/javascript">
/* <![CDATA[ */
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-309831-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
(function(b){(function(a){"__CF"in b&&"DJS"in b.__CF?b.__CF.DJS.push(a):"addEventListener"in b?b.addEventListener("load",a,!1):b.attachEvent("onload",a)})(function(){"FB"in b&&"Event"in FB&&"subscribe"in FB.Event&&(FB.Event.subscribe("edge.create",function(a){_gaq.push(["_trackSocial","facebook","like",a])}),FB.Event.subscribe("edge.remove",function(a){_gaq.push(["_trackSocial","facebook","unlike",a])}),FB.Event.subscribe("message.send",function(a){_gaq.push(["_trackSocial","facebook","send",a])}));"twttr"in b&&"events"in twttr&&"bind"in twttr.events&&twttr.events.bind("tweet",function(a){if(a){var b;if(a.target&&a.target.nodeName=="IFRAME")a:{if(a=a.target.src){a=a.split("#")[0].match(/[^?=&]+=([^&]*)?/g);b=0;for(var c;c=a[b];++b)if(c.indexOf("url")===0){b=unescape(c.split("=")[1]);break a}}b=void 0}_gaq.push(["_trackSocial","twitter","tweet",b])}})})})(window);
/* ]]> */
</script>
</head>
<body onload="detectar()">
<h1>Ejemplo de geolocalizacion basado en HTML5</h1>
<div id="mapa">
</div>
<script src="http://code.google.com/apis/gears/gears_init.js" type="text/javascript" charset="utf-8"></script>
<script src="geo.js" type="text/javascript" charset="utf-8"></script>
<script language="javascript">
function detectar(){
if(geo_position_js.init())
{
document.getElementById('mapa').innerHTML="Leyendo...";
geo_position_js.getCurrentPosition(mostra_ubicacion,function(){document.getElementById('mapa').innerHTML="No se puedo detectar la ubicación"},{enableHighAccuracy:true});
} else {
document.getElementById('mapa').innerHTML="La geolocalización no funciona en este navegador.";
}
}
function mostra_ubicacion(p){
var coords = p.coords.latitude + "," + p.coords.longitude;
document.getElementById('mapa').innerHTML="<p>latitud="+p.coords.latitude.toFixed(2)+" longitud="+p.coords.longitude.toFixed(2) + "</p>"
+"<img src=\"http://maps.google.com/maps/api/staticmap?center="+coords+"&maptype=hybrid&size=400x400&zoom=12&markers=size:mid|"+coords+"&sensor=false\" alt=\"mapa\"/>";
}
</script>
</body>
</html>
Nevertheless, this code returns a map with the user's geographic coordinates (latitude/longitude).
Is it there an easy way to determine this and use that information in a form's field?
Thanks in advance.
Another stackoverflow question talked about a webservice that allows for geolocation based on IP address
You could use this to implement a server-side solution that generates the markup with their location filled in.
The old fashioned (and still prevalent!) way is to do a reverse lookup of the client IP address :)
The HTML5 geolocation API will get you the user's latitude and longitude (assuming they opt in). If you need to get info such as the city, country, or postal code, you'll need to use a reverse-geocoding web service. There are plenty of those out there:
Google
Bing
etc
So take your pick... just make sure to look at the terms & conditions and be sure you won't be in violation once the site goes live.
You should be able to find code samples by googling around a bit, it's a fairly common use case. The steps will be:
Get the user's lat/lng with your existing code.
Make an AJAX (JSONP) call to request the reverse-geocode (use your Geocode provider to figure out what URL to use. eg, for Google it is like this).
Parse the JSON response to extract the info you need (country, city).
I'm using jquery mobile and phonegap to create an android application. I followed the short guide "20 Recipes for Programming Phonegap" which recommends using a callback from a custom script loaded on index.html to a function named onPageLoad() where Page is the name of the destination page's html file.
I'm stuck however, because the javascript, which I included inside the data-role="page" div with a script tag, is not loading.
https://stackoverflow.com/a/8838639/153382 points to the jQuery mobile guide that says this should work. I've read the guide, it's not working. Now what?
Has something changed with jquery mobile that makes this no longer work?
Update
Some testing shows that inline scripts run, but the script src attribute is not being evaluated for the script I am trying to load from a file.
also tried <script type="text/javascript">$.getScript("js/lookup.js");</script>. It did not work either.
code
common.js included on index.html after <div data-role="page">...</div>:
<script type="text/javascript" charset="utf-8" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery.mobile-1.1.0.min.js"></script>
<script type="text/javascript" charset="utf-8" src="js/common.js"></script>
relevant contents of common.js:
function executeCallback() {
if (isPhoneGapReady) {
// get name of current html page
var pages = currentUrl.split("/");
var currentPage = pages[pages.length - 1].
slice(0, pages[pages.length - 1].indexOf(".html"));
// captalize the first letter and execute the function
currentPage = currentPage.charAt(0).toUpperCase() +
currentPage.slice(1);
if (typeof window['on' + currentPage + 'Load'] ==
typeof(Function)) {
window['on' + currentPage + 'Load']();
}
alert('on' + currentPage + 'Load: ' + typeof window['on' + currentPage + 'Load']);
// says onLookupLoad: undefined
}
}
$(document).bind("pageload", function(event, data) {
init(data.url);
});
window.onload = init;
init(url) calls onDeviceReady() which calls executeCallback()
lookup.html includes the following line inside <div data-role="page">:
<script type="text/javascript" charset="utf-8" src="js/lookup.js"></script>
Seems as if the issue was that Eclipse was not generating a new apk. I guess this is because the assets directory changed, but the src directory had not. If I delete the apk in the bin folder and run the emulator my code works as designed.
I'm trying to embed a column3d chart from fusioncharts in my MonoTouch project using UIWebView. I've added the necessary outlets and tested by using loadrequest to load a url and loadHtmlString to format a simple line of text. This works fine. I even tested that fusionchart works correctly on my browser using the below code and it does.
I have a folder named "charts" in my MonoTouch project that contains, Column3d.swf, jquery.min.js, FusionCharts.js, FusionCharts.HC.js and FusionCharts.HC.Charts.js.
In my
ViewDidLoad
string htmlString = "<html>
<head>
<script type=\"text/javascript\"src=\"Charts/jquery.min.js\">
</script>
<script type=\"text/javascript\" src=\"Charts/FusionCharts.js\">
</script>
<script type=\"text/javascript\" src=\"Charts/FusionCharts.HC.js\">
</script>
<script type=\"text/javascript\" src=\"Charts/FusionCharts.HC.Charts.js\">
</script>
</head>
<body>
<div id=\"chartContainer\">FusionCharts will load here!
</div>
<script type=\"text/javascript\"> var myChart = new FusionCharts( \"Charts/Column3D.swf\", \"myChartId\", \"400\", \"300\", \"0\", \"1\" );myChart.setXMLUrl(\"Charts/Data.xml\");
myChart.render(\"chartContainer\");
</script>
</body>
</html>";
this.webView.LoadHtmlString (htmlString, new NSUrl ("./Charts", true));
/*string htmlString = "<html><head></head><body><span style=\"font-weight: bold;\">This</span> " +
"<span style=\"text-decoration: underline;\">is</span> <span style=\"font-style: italic;\">some formatted</span> " +"<span style=\"font-weight: bold;text-decoration: underline;\">text!</span><br></body></html>";*/ //works
//this.webView.LoadHtmlString (htmlString, null); //works
Data.xml
<chart caption='Weekly Sales Summary'
xAxisName='Week' yAxisName='Amount' numberPrefix='$'>
<set label='Week 1' value='14400' />
<set label='Week 2' value='19600' />
<set label='Week 3' value='24000' />
<set label='Week 4' value='15700' />
</chart>
Can someone explain how I can get this working? Thanks in advance.
EDIT: I also tried
string htmlString = "<html><head> <title>Creating Pure JavaScript chart</title><script type=\"text/javascript\" src=\"charts/FusionCharts.js\"></script></head> <body><div id=\"chartContainer\">FusionCharts will load here!</div> <script type=\"text/javascript\">FusionCharts.setCurrentRenderer('javascript');var myChart = new FusionCharts( \"charts/Column3D.swf\", \"myChartId\", \"400\", \"300\", \"0\", \"1\" );myChart.setXMLData(\"<chart><set label='Data1' value='1' /></chart>\"); myChart.render(\"chartContainer\"); </script></body> </html>";
where i force the renderer to use javascript and set the chart parameters in the string to no avail. Anyone?
I solved my issue and thought I would post it should someone run into a similar issue.
The first thing I did was to right click on each of my javscript files ie FusionCharts.js, FusionCharts.HC.js and FusionCharts.HC.Charts.js and set their build type to content.
I then told Monotouch the build path for the charts would be contained in the charts folder by declaring
string path = NSBundle.MainBundle.BundlePath + "/Charts/";
Since I declare i am going to look in the Charts folder for related files, I then had to amend my htmlString by removing the "charts" keyword reference from all the "src" as below (since we are already lo.
string htmlString = "<html>
<head>
<script type=\"text/javascript\" src=\"jquery.min.js\">
</script>
<script type=\"text/javascript\" src=\"/FusionCharts.js\">
</script>
<script type=\"text/javascript\" src=\"/FusionCharts.HC.js\">
</script>
<script type=\"text/javascript\" src=\"FusionCharts.HC.Charts.js\">
</script>
</head>
<body>
<div id=\"chartContainer\">FusionCharts will load here!
</div>
<script type=\"text/javascript\"> var myChart = new FusionCharts(\"Column3D.swf\", \"myChartId\", \"400\", \"300\", \"0\", \"1\" );myChart.setXMLUrl(\"Charts/Data.xml\");
myChart.render(\"chartContainer\");
</script>
</body>
</html>";
I then call the loadHtml string method as below with the second argument pointing to the path that contains the javascript files.
this.webView.LoadHtmlString(htmlString, new NSUrl(path, true));
I even tested that fusionchart works correctly on my browser using the below code and it does.
Did you test this with an iOS device running Safari ?
project that contains, Column3d.swf,
That looks like a Flash file and iOS (and WebKit) does not support flash.
The website hints of an HTML5 version - so if they support flash-less browser then you should be able to do what you want using MonoTouch (or anything in iOS) using FusionChart. Otherwise you might need to look at other charting products (or a server-side solution).
FusionCharts had put out a blog post showing how to get HTML5 charts in iOS devices.
Have a look at it here - http://blog.fusioncharts.com/2012/02/create-charts-for-iphone-and-ipad-apps-using-fusioncharts-xt/