I'm doing a work for school, and I'm doing a online plataforn to buy games online, I can just use HTML, CSS and JS so for each game e have a JS file with the informations, here is an example:
/*doom.js*/
var info = {
title : "doom",
price : "59.99",
off : "0%"
};
And my html page is that one:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="games/functions.js"></script>
</head>
<body>
<label id="title"></label>
</body>
</html>
I have that page to all my games, so I use the GET method to know wich file I need to read. (game.html?id=doom)
I have this code to get the id chosed and load the file:
window.onload = function() {
id = getURLParameter('id');
loadGamefile("games/"+id+".js");
};
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
function loadGamefile(filename){
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref);
loadinformation();
}
function loadinformation(){
document.getElementById("title").innerHTML = info.title; //info.title is from the doom.js file
}
The only problem is he dont change the label, but if I put a button on the btml code and onclick I say its the loadinformation() he load fine, but I want that automatic when the page loads and here is the error I get from console: functions.js:22 Uncaught ReferenceError: info is not defined, I think maybe is becouse the browser didn't had time to load the file, I don't know, can someone help me? Thanks and sorry for my english.
The problem is you aren't giving the browser a chance to parse your new script. You can give it a moment to do that using setTimeout.
function loadGamefile(filename) {
// your other code goes here
setTimeout(function() {
loadinformation();
}, 500); // wait half of a second
}
Ideally, you should have your data stored in a JSON file then load it using AJAX instead. There are numerous tutorials covering how to load JSON over AJAX.
As #Bergi pointed out, this solution is very fragile and relies on the script loading in under 500ms. Instead, you can listen for the load event to ensure you use the script as soon as it's ready.
function loadGamefile(filename) {
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref);
// Wait for the script to load
fileref.onload = function() {
loadinformation();
};
}
Related
I have successfully embedded javascipt with jQuery into a page in SharePoint and I am trying to write a function that, when called on load, obtains the data from an excel file that has been uploaded into the SharePoint's library, so that I can manipulate it with JavaScript and push it into a SharePoint List. My issues are coming from that first part. I have attempted to do this with the following code, which was obtained from SharePoint's documentation and modified to use the ".fail" function instead of the deprecated ".error" function:
function readFile() {
var clientContext;
var oWebsite;
var fileUrl;
clientContext = new SP.ClientContext.get_current();
oWebsite = clientContext.get_web();
clientContext.load(oWebsite);
clientContext.executeQueryAsync(function () {
fileUrl = "My file's url as obtained from SharePoint";
$.ajax({
url: fileUrl,
type: "GET"
})
.done(Function.createDelegate(this, successHandler))
.fail(Function.createDelegate(this, errorHandler));
}, errorHandler);
function successHandler(data) {
console.log(data);
}
function errorHandler() {
console.log("Request failed: " + arguments[2]);
}
}
This appears to work, as I receive no errors and the data is indeed displayed in the console. However, instead of the file's contents, I see this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name='viewport' content='width=device-width, initial-scale=1' />
<meta name='robots' content='noindex' />
<link rel="shortcut icon" href="http://spoos-16-rdn.bankofamerica.com/wv/resources/1033/FavIcon_Word.ico" />
<title>Document.docx</title>
<script type="text/javascript">
var WOPIPerf_UserClick = null;
if (window.sessionStorage)
{
WOPIPerf_UserClick = window.sessionStorage.getItem("WOPIPerf_UserClickTime");
window.sessionStorage.removeItem("WOPIPerf_UserClickTime");
}
</script>
<script type="text/javascript">
function ULS6zp(){var o=new Object;o.ULSTeamName="Microsoft SharePoint Foundation";o.ULSFileName="WOPIFrame.aspx";return o;}
function getWopiIFrameElement()
{ULS6zp:;
return document.querySelector("iframe[name=WebApplicationFrame]");
}
function WACRedirector()
{ULS6zp:;
var myFrame = getWopiIFrameElement();
myFrame.id = "WebAp
I'm not sure what's going on, but I feel like there's a step missing here. When I enter the url into my browser, it redirects to SharePoint's in-house document editor, where I can indeed see the document's contents and even edit it. Is there something else I need to do to obtain the file's actual content in JavaScript?
You need to use the URL to the file, not the URL to Office Online's viewers/editors. The direct URL should look something like this:
https://yourDomain/sites/yourSite/yourLibrary/yourFileName.xlsx
https://yourDomain/sites/yourSite/yourLibrary/yourFolder/yourFileName.xlsx
When entered in a browser, this URL should start a download.
I found the answer: The query url needs to utilize the ExcelRest API built into SharePoint. To do this, I simply had to add "/_vti_bin/ExcelRest.aspx/" to the url in the following fashion:
https://yourDomain/sites/yourSite/yourLibrary/_vti_bin/ExcelRest.aspx/yourFolder/yourFileName.xlsx
I have a html page with this on it.
var accountid = getParameterByName("AccountId");
var account = null;
if (accountid != null)
{
account = GetEntity("Account", accountid, "Name, piv_BusinessUnit, AccountId");
}
At the bottom of that same page is this
<script src="js/datasource.CRM.js"></script>
Within that file is this
function GetEntity(logicalName, id, columnSet)
{
return RunQuery(logicalName + "Set?&$filter="+logicalName+"Id eq guid'{" + id + "}'" + "&$select="+columnSet);
}
When running the page I get this error
Uncaught ReferenceError: GetEntity is not defined
Does anyone know any reason why a Javascript function is not found when it is there???
When including script tags that loads external scripts, they are only parsed as encountered in the DOM, and as such hoisting won't work across script tags.
In other words, you have to include the script, before actually trying to use it.
Here's the classis example, using jQuery before it's included, and failing
<script type="text/javascript">
$('#epic fail').addClass('wont_work'); // $ is not defined error
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
i have use docx.js for generate docx file, but generaeted docx doenot open. my generated docx file output is
i have included following js file into my Html page
<script type="text/javascript" src="js/Docx/jszip.js"></script>
<!-- Include main js lib -->
<script type="text/javascript" src="js/Docx/DOCX.js"></script>
and javascript function is
function test() {
//alert("test fn call");
var doc = new DOCXjs();
doc.text('DOCX.js is a free open source library for generating Microsoft Word Documents using pure client-side JavaScript.');
//doc.text('It was developed by James Hall at Snapshot Media.');
var output = doc.output('datauri');
}
when i click button this function will be calling, and also i want to add datatable as a content of word document so how to add content using Docx.js?
Probably you are trying to use the docx.js without server, that will not work because it can't load the necessary files.
if you are executing the code on a server then edit the path of '/blank/' somewhere in the docx.js file
$.ajax({
url: '/blank/' + files[file],
complete: function(r) {
//file_data[this.url.replace(/blank_/, '')] = r.responseText;
zip.add(this.url.replace('/blank/', ''), r.responseText);
file_count_current ++;
if (file_count == file_count_current) {
doOutput();
}
}
});
I am currently contracted to a place that cannot use a CMS or PHP, but they want me to build something like a CMS using HTML and JavaScript.
I know it sounds ridiculous but I do not want to be searching for another job these days and they are the nicest people that I have ever worked for - EVER - and I old.
One of the concepts of a CMS is to have global files that you can include at any given time.
As a result, I tried the $.ajax, $.get, etc..., but I was running into issues of Access URI denied and those kind of things for trying to load a file which is one directory level the current directory.
I was able to get the javascript file to load by using the old XMLHttpRequest/ActiveXObject.
However, the script within the div that has been loaded cannot be called. I receive an error of "Can't find variable: mFunc" which is the name of the function that has been loaded into the div.
Here's the code for my html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>retrieve local file one level up</title>
<script type="text/javascript">
<!--
var createRequestObject = function(){
var req;
if(window.XMLHttpRequest){
// Firefox, Safari, Opera...
req = new XMLHttpRequest();
}else if(window.ActiveXObject){
// Internet Explorer 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
}else{
alert('There was a problem creating the XMLHttpRequest object');
}
return req;
}
// Make the XMLHttpRequest object
var http = createRequestObject();
var sendRequestPost = function(){
var jscript = '../test.js';
// Open PHP script for requests
http.open('GET', jscript);
http.setRequestHeader('Content-Type', 'text/javascript');
http.onreadystatechange = handleResponsePost;
http.send(null);
var mT = setTimeout("mFunc()", 2000);
}
var handleResponsePost = function(){
if(http.readyState == 1){
document.getElementById('mDiv').innerHTML = "Please wait, loading... " ;
}else if(http.readyState == 4 && http.status == 200){
// Text returned from PHP script
var response = http.responseText;
document.getElementById('mDiv').innerHTML = response;
if(response){
// Update ajaxTest2 content
document.getElementById('mDiv').innerHTML = response;
}
}else if(http.readyState == 2){
document.getElementById('mDiv').innerHTML = http.responseText;
}else if(http.readyState == 3){
document.getElementById('mDiv').innerHTML = http.responseText;
}
}
-->
</script>
</head>
<body onload="javascript:sendRequestPost();">
<div id="mDiv"></div>
</body>
</html>
Here is the javascript that loads just fine into mDiv:
<script type="text/javascript">
<!--
var mFunc = function(){
var mScript = document.createElement("script");
mScript.setAttribute("type","text/javascript");
var data = 'alert("gets here");'
mScript.text = data;
var head = document.getElementsByTagName("head")[0];
head.appendChild(mScript);
}
-->
</script>
Yet, after the two seconds have passed, I receive the error.
I am sure that it is probably because the browser just sees this as text within the div, so how do I make it recognize that it is javascript.
I have tried using eval, which I do not want to use, but even returns a parse error.
Thanks in advance
../ has meaning to the local filesystem (on most platforms), but not to HTML or to most webservers. Remember that the URL is just a query string for the server.
Generally speaking, you need to parse the URL to remove the undesired few elements. If you just want scripts that are common across the website, though, they should be referenced from the root, so the relative URL would begin with /.
A quick hack would be /(.*)\/.*/.exec( '/foo/bar/baz.html' )[1]. This doesn't handle the query string following ? or anchor following # but you won't have a query on a static website, and won't have anchors until you get into more advanced techniques. jQuery has a better utility for parsing URLs, also based on regexps.
It's offtopic for this site, but you will have to be very familiar with XHR to implement a JavaScript CMS.
OK, another programmer that I work with, has found a simple solution.
Instead trying to use ajax to load a JavaScript file from a higher directory level and then run a document.writeln or document.getElementById("someDiv").innerHTML -- reverse the steps.
Include the JS file as you would normally:
<script type="text/javascript" src="../../common/header.js"></script>
Within this JS file
function CommonHeader(mPath) {
document.writeln('<header>');
document.writeln(' <div class="PageWidth">');
document.writeln(' <h1>Something<sup>®</sup> <em>Learn about us</em></h1>');
document.writeln(' <nav>');
document.writeln(' <ul>');
document.writeln(' <li id="loginOut"></li>');
The order needs to be for you to call document.writeln at the beginning of the process.
We can now load header.js, footer.js, and whatever other file that we wish to load, along with having an array at the top of each page denoting the path to those files, for lower directory level htmls
dynamicPathArr[0] = "../../";
Then within whatever file, you can call the function to write the date into the page
<script type="text/javascript">CommonHeader(dynamicPathArr[0])</script>
I cannot believe that I did not think of this completely simple solution.
Although this is not SEO friendly, it is good for only updating header, footer, nav, etc... in one location, until everything is finalized.
And thanks you for the response
I want to use Google API inside a js file and how can I use it? I tried to use google.load() directly in the js file but was told that google is not defined. Then I tried to use the following code
var s = document.createElement('script');
but was told that document is not defined.
What should I do to use google api inside a js file? Thank you.
Here what I want to use is the Google Feed API.
The html code I used is
<!DOCTYPE HTML>
<html>
<head>
<title>
Example
</title>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
</head>
<body>
<div>
<p id="computation_results">please wait, computing … </p>
</div>
<script>
var worker = new Worker('numberworker.js');
worker.postMessage({first:123,second:456});
worker.onmessage = function (event)
{
alert(event.data);
document.getElementById('computation_results').textContent = event.data;
};
</script>
</body>
</html>
and the js file where I want to use the api is
// Our callback function, for when a feed is loaded.
function feedLoaded(result) {
if (!result.error) {
var container = document.getElementById("content");
container.innerHTML = '';
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
}
function OnLoad() {
var feed = new google.feeds.Feed("http://www.digg.com/rss/index.xml");
feed.load(feedLoaded);
}
onmessage = function (event)
{
var fileref=document.createElement('script');
var filename="https://www.google.com/jsapi";
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
document.getElementsByTagName("head")[0].appendChild(fileref);
// google.load("feeds", "1");
// google.setOnLoadCallback(OnLoad);
var first=event.data.first;
var second=event.data.second;
postMessage("Work done! "+ " "+first+" "+second);
};
You need to include the API before you can use it. Try putting this in your head block:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
To load the feed API, you can then have another script block like this:
<script type="text/javascript">
google.load("feeds", "1");
var feed = new google.feeds.Feed("<<url here>>");
...
</script>
I would check to make sure your html is validated first, or put up a link to a test file. Any slightest error can cause you to get any number of errors. I tried the following code in a file by itself, wrapped in tags, and was able to load the api. To load a javascript file using javascript you would use the following
var fileref=document.createElement('script');
var filename="https://www.google.com/jsapi";
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
document.getElementsByTagName("head")[0].appendChild(fileref);
Then after it you use the api calls
google.load(....)\
EDIT:
You are using html5 web workers, that use process outside of the browser, to create a script. This is not possible due to html5 workers do not have access to the DOM. http://www.sitepoint.com/javascript-threading-html5-web-workers/
You would have to create it outside of the worker or include in a script element