I was working on a very simple page which just pulls and displays images from a table in parse.com. I do not have much experience with javascript which might be evident from the code below.
I need the images to show up in a chronological order. With the current code, it works fine most of the times but is a little buggy.
There are 2 main problems:
1) Sometimes, randomly, one particular new image might not come on the top and instead show up somewhere in between.
2) This page works on Firefox and Chrome but NOT on IE.
Is there a better way to implement this or is there something that I should change? Any help would be appreciated.
Page source-
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js"></script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url;
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});
</script>
</body>
</html>
Internet Explorer blocks mixed content. Since Parse's JavaScript SDK requires SSL, you need to host your app using HTTPS as well in order to access it from IE.
Hey you made one mistake. it was not working for me. Then i found that it is url() not url.
The amendment is img.src = results[i].get("image").url();
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js">
</script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url();
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});
Related
I have a body onload calling a function in javascript. I Have tried many things, but the console just prints to the error log:
uncaught reference error: resetLoginForm is not defined
My code is as follows:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<title>Login Page</title>
<script src="/client/js/popper.min.js"></script>
<script src="/client/js/js.cookie.min.js"></script>
<script src="/client/js/querystring.js"></script>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" media="screen,projection"/>
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<script type="module" src="js/login.js"></script>
</head>
<body class="blue-grey darken-2" onload="resetLoginForm()">
<script src="js/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
This is the JavaScript code that I am trying to use:
import * as Cookies from "/client/js/js.cookie.min.js";
function resetLoginForm() {
if (Cookies.get("destination") === undefined) {
window.location.href = "/client/index.html";
}
const loginForm = $('#loginForm');
loginForm.submit(event => {
event.preventDefault();
$.ajax({
url: '/admin/login',
type: 'POST',
data: loginForm.serialize(),
success: response => {
if (response.startsWith('Error:')) {
alert(response);
} else {
Cookies.set("sessionToken", response);
window.location.href = Cookies.get("destination");
}
}
});
});
You're using new ECMAScript modules (<script type="module" ...>), which are isolated to their own scope. Your function resetLoginForm() isn't being defined in the global scope (Where you can essentially call it from your onload body function). You need to define it explicitly in your module:
import * as Cookies from "/client/js/js.cookie.min.js";
window.resetLoginForm = {
if (Cookies.get("destination") === undefined) {
window.location.href = "/client/index.html";
}
...
Ideally though, you should not be using onload at all. Just add an event listener in:
import * as Cookies from "/client/js/js.cookie.min.js";
function resetLoginForm() {
if (Cookies.get("destination") === undefined) {
window.location.href = "/client/index.html";
}
...
}
// Attach an event, and call resetLoginForm when the document is done loading.
document.addEventListener("DOMContentLoaded", resetLoginForm);
Change is <script type="text/javascript" src="js/login.js"></script>
Cnages is please check once resetLoginForm function in onload.
I'm trying to use cordova-plugin-file-opener2 to load a pdf in Cordova. I can't seem to get it to work in the browser or on Android.
Here is my app.js file:
(function () {
document.querySelector('#file-button').addEventListener('click', openFile);
function openFile(){
console.log('opening file');
console.log(cordova.file.applicationDirectory);
var fileName = 'www/assets/pdf/foo.pdf';
var pathToFile = cordova.file.applicationDirectory + fileName;
window.resolveLocalFileSystemURL(pathToFile, function (entry) {
cordova.plugins.fileOpener2.open(
entry.toInternalURL(),
'application/pdf', {
error: function (e) {
alert.log('Error status: ' + e.status + ' - Error message: ' + e.message);
},
success: function () {
alert.log('file opened successfully');
}
}
);
}, function (e) {
alert('File Not Found');
});
}
}());
And here's the html:
<!DOCTYPE html>
<html>
<head>
<script src="cordova.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<p><button id="file-button" class="help-btn">Help</button></p>
<div class='header'><h1>Directory</h1></div>
<div class='search-view'>
<input class='search-key' type="search" placeholder="Enter name"/>
<ul class='list employee-list'></ul>
</div>
<script src="lib/jquery.js"></script>
<script src="js/services/memory/EmployeeService.js"></script>
<script src="js/app.js"></script>
</body>
</html>
When the 'file-button' is clicked, it triggers the openFile function.
This shows me the following in the console:
adding proxy for Device cordova.js:1010:9
adding proxy for File cordova.js:1010:9
opening file app.js:6:9
"http://localhost:8000/" app.js:7:9
And the alert message says 'File not found'.
App.js is located in www --> js
foo.pdf is located in www --> assets --> pdf
Im trying to call a function from another js file that is located in the same application directory as my main js script and html file. I receive an error claiming that the referenced function does not exist. I have referenced both of the scripts in the main html file in the proper order but cant for the life of me figure out why it cannot detect the function. I can only assume it has something to do with how dojo parses through the files and have experimented with both its dojo/domReady! and dojo/ready modules in hopes to force scripts to load. I feel like this should be much simpler than Im making it out to be. Any help would be greatly appreciated.
html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Asset View</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://js.arcgis.com/3.14/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.14/esri/css/esri.css">
<link rel="stylesheet" href= "styles/styles.css">
<script src="http://js.arcgis.com/3.14/"></script>
<script src="scripts/requests-js.js"></script>
<script src="scripts/layout-js.js"></script>
<script src="scripts/xmain-js.js"></script>
</head>
<body class = "claro">
</body>
</html>
requests-js.js
require(["dojo/dom","dojo/on","dojo/request","dojo/json","dojo/parser","dojo/ready"
], function(dom,on,request,JSON,parser,ready) {
ready(function() {
console.log("request start");
function sendRequest (url,assetCode,fromDate,toDate) {
console.log("Request innit");
request(url,{
method: "POST",
handleAs: "json",
headers: {"Content-Type": "application/json"},
data: JSON.stringify(
[
{
"AssetCodes": assetCode,
"FromGasDay": fromDate,
"ToGasDate": toDate
}
]
)
}).then(function(resp){
console.log(JSON.stringify(resp));
var naStorageJSON = resp;
});
}
console.log("request end");
});
});
main-js.js
require([
"dojo/dom","dojo/on","dojo/parser","dojo/json","dojo/request","dojo/ready"
], function(dom,on,parser,JSON,request,ready) {
ready(function() {
console.log("Main Start");
var url = "http://*********";
var assetCode = ["**"];
var toDate = "****";
var fromDate ="*****";
on(dom.byId("senecaLakeBtn"),"click", sendRequest(url,assetCode,toDate,fromDate));
console.log("Main End");
});
});
The issue is scope here. By declaring an empty array at the top of the js script (outside of its successive functions) the function can be accessible to other scripts in the application.
var app = [];
require(["dojo/dom","dojo/on","dojo/request","dojo/json","dojo/parser","dojo/ready"
], function(dom,on,request,JSON,parser,ready) {
ready(function(){
app.sendRequest = function sendRequest (url,assetCode,fromDate,toDate) {
...
...
}
}
it can them be called upon from other scripts by referencing
app.sendRequest(arg1,arg2,arg3);
I have the following HTML code in a file called test.html. Both the HTML file and the JSON file below are stored on a server within the same directory.
<!DOCTYPE html>
<html>
<head>
<title>Shape Up</title>
<meta name="robots" content="noindex,follow">
<meta name="description" content="">
<meta name="keywords" content="">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="JavaScript" type="text/javascript">
function ajax_get_json()
{
var hr = new XMLHttpRequest();
hr.open("GET", "game.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function()
{
if(hr.readyState == 4 && hr.status == 200)
{
var data = JSON.parse(hr.responseText);
var results = document.getElementById("results");
results.innerHTML = "";
for(var obj in data)
{
results.innerHTML += data[obj].title;
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script language="JavaScript" type="text/javascript">
ajax_get_json();
</script>
</body>
</html>
It pulls data from a file called game.json which is stored in the same directory.
{
"level_001":
{
"id":001,
"title":"Level 1",
"difficulty":0,
"comments":"this is how you complete level 1"
},
"level_002":
{
"id":002,
"title":"Level 2",
"difficulty":0,
"comments":"this is how you complete level 2"
}
}
The problem is that the results.innerHTML = ""; line is never reached. Why?
There are no errors in the browser, I've checked this on Firefox and on Safari.
According to jsonlint.com your JSON is invalid because of these properties:
"id":001
...
"id":002
You need to either remove the leading zeros:
"id":1
or make the numbers strings:
"id":"001"
For further details see the format rules spelled out at json.org
Presumably the line you mentioned is never reached because JSON.parse() gives an error about the above. (Do you not see an error in the browser's console?)
I am trying to download an apk file on a button click using phonegap. Why does this code not work? Nothing happens when I click Download. Could someone point me in the right direction? Thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script charset="utf-8" src = "jquery-1.10.1.min.js"></script>
<script charset="utf-8" src = "cordova-2.7.0.js"></script>
<script>
function foo()
{
var fileTransfer = new FileTransfer();
fileTransfer.download(
"http://samplewebsite.com/example.apk",
"file:///sdcard/example.apk",
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
}
);
}
</script>
</head>
<body>
<button onclick="foo()">Download</button>
</body>
</html>
var fileTransfer = new FileTransfer();
var uri = encodeURI(url);
var filePath= "/sdcard/directory/file.extension";
fileTransfer.download(uri,filePath,
function(entry) {
//success
},
function(error) {
//failed
}
);
This worked for me
Your code works fine.
This seems stupid but have you tried to use alert() instead of console.log() in the callbacks?
If you are sure the callback code is not invoked try to run just the app created by the phonegap' create script and check that the device is ready before doing other tests.
just my 2c