Read a JSON gist as a query string - javascript

I currently have a Javascript application that consists of three files:
index.html
app.js
input.json
The input.json file gets referenced several times by the app.js file, in order to render content into divs in the index.html file.
I want to make it so that loading my index.html at http://example.com/myapp can take an externall hosted JSON as the source for app.js to read, like myexample.com/myapp?myhost.com/files/input.json.
Can anybody advise me on how to get this working?

For this to work, you need to enable CORS on myexample.com.
Assuming you are using jQuery. (Take a look at here if you don't want to use jQuery for ajax requests)
$.get('http://myexample.com/myapp?myhost.com/files/input.json')
.done(function(data) {
// use external 'data' here.
})
.fail(function() {
// handle error here
});

Related

Raw Github js file not loading (direct link) like CDN

I created a coding library for the public to use by putting a <script> tag in the <head> tag on the page but when I try to use the a function it says undefined when it ran.
. I linked the url to the index.js file but it doesn't load it to the client user.
<head>
<script src="https://github.com/McJoe21/coderslib/blob/master/index.js"></script>
</head>
When I run a console.log(ranInteger(1,10)) which I have defined in my index.js file but I get a ranInteger is not defined error. All help is welcome!
Technically speaking, GitHub doesn't allow source code to be accessed from their site like a CDN, however from This StackOverflow Question, there is a workaround. I wouldn't recommend using it, but you can use "https://cdn.jsdelivr.net/gh/" to get your script to work (from user #anayarojo on StackOverflow).
The url in your case would look like this:
https://cdn.jsdelivr.net/gh/McJoe21/coderslib/index.js
The pattern for the URL is:
https://cdn.jsdelivr.net/gh/<username>/<repository>/<file>
You cannot load JavaScript from raw version of Github because the content type(MIME type) is text/plain, not application/javascript or text/javascript. This is to stop you using Github as a CDN. Still you can achieve serving raw file as cdn in the following way, using cdn.jsdelivr.net.
https://cdn.jsdelivr.net/gh/<github-username>/<github-repo-name#branch-name>/<filename>
If file is at main branch, no need to include in branch section after #. If you mention also, it'll work.
For more reference
The file you're attempting to import is a GitHub viewer for a file. To import the raw data for that file, you'd want to use this code:
<script>
const source = 'https://raw.githubusercontent.com/McJoe21/coderslib/master/index.js';
fetch(source).then((response) => {
return response.text()
}).then((response) => {
eval(response);
}).catch((error) => {
console.error(`An error occured while attempting to load the "${source}" resource!`);
console.error(error);
});
</script>
Since GitHub does not directly allow the import of their user content, you will need to wrap your source URL in the above fetch-eval block.

Using external js libraries in sapui5

So I'm trying to inlcude an external .js file in my SAPUI5 Controller.
jQuery.sap.includeScript("externalLibrary.min.js",
function() {
//initalizing objects from library
});
However, the callback which should be called once the script is loaded, never gets called. The error message it gives me is:
"externalLibrary.min.js:16 Uncaught TypeError: Cannot read property
'Constructor' of undefined"
Whats another way I could do this? I was looking into jQuery.sap.registerModulePath() and jQuery.sap.registerResourcePath() but couldn't find a good example of the use of these nor an explaination of the difference between the two online.
Thanks a lot!
You can try jQuery.sap.includeScript(vUrl, sId?, fnLoadCallback?, fnErrorCallback?)
https://sapui5.hana.ondemand.com/docs/api/symbols/jQuery.sap.html#.includeScript
in fiori launchpad based app , we use component.js as root , so we don't have index.html to include scripts (if you use XML view instand of HTML view).
try
jQuery.sap.includeScript({
url: "https://maps.googleapis.com...",
id: "IncludeGoogleMapsScript"
}).then(function() { ... })
Not working in portal service , fallback is provided :
UsingjQuery.sap.includeScript().then() in HCP Firori Launchpad
You can use jQuery.sap.registerResourcePath('lib', URL) and then jquery.SAP.require('lib.file'). You can do both one after another or register in the init and later require. Does not matter. I don't have an example at hand as I am on a phone but it works. What you need to keep in mind is that this example would load something like URL/file.js so you need to adjust accordingly. The name you give to the lib does not matter.
You can also inject a script tag into the current page ,however, the require will load the external lib synchronously while if you inject a script tag you need to wait until it is loaded with a callback.
PS: the capitalization on those methods is not right
Got it! For future reference, it works to load the files from the index html like so:
<script src="library.js"></script>
The main problem was that I was trying to include external dependencies which also contained jQuery. So, I had to remove that from the file and now it's working.

Read .csv file to object/array in javascript

I'm trying to do something that I think is fairly simple, but doesn't seem to be working. I have a .csv file in the same directory as my script file. I want to create an object or an array using the data from the .csv file. How do I access the local file using javascript?
Sorry for the lack of code, but I don't even know which route to go down; I've tried .get and ajax and this plugin but I just don't know what I'm doing. Could someone give me a clear example of how to load the file and print it in a div?
In order to simulate a static file server, you can run an http server using python on the command line. This is necessary to use ajax requests.
python -m SimpleHTTPServer
Or if you have python 3
python -m http.server
Now there are two parts to getting that file to a webpage. 1) make an ajax request, 2) parse the csv. There are many different libraries that implement ajax requests, but in this case you might find the easiest out of the box solution which combines both is d3.js.
d3.csv("filename.csv", function(err, data) {
// csv is parsed into an array of objects, as data
});
Of course this will only work if you are loading your page from localhost.
EDIT:
Make sure you run your http server from the location of your index.html file. then the request you make in the d3.csv function is relative to index. finally, the data is only available inside the callback, and any error message (or null) will be put inside the err argument.
Project
|
+-- index.html
|
+-- data
| |
| \-- dataset.csv
Then the code in index.html would look like
d3.csv("data/dataset.csv", function(err, data) {
if (err) console.log(err) // error messages
console.log(data); // should contain the parsed csv
});
PapaParse() does an excellent job here, for example this will do the job for you:
Papa.parse(file, {
complete: function(results) {
console.log("Finished:", results.data);
}
});
DEMO

bootstrappedUser - Jade or EJS to HTML

I've been doing some guide on Mean stack and I came to a point where I'm currently stuck.
Following this guide, I have created a simple authentication where I'm able to log in using Passport JS. Whatsoever, each time when page refreshes, the authentication gets restarted (client doesn't recognise it anymore).
Since this is suppose to happen in the guide and we are about to fix it, guide said the following.
1. Create a Jade file and insert this:
if !!bootstrappedUser
script.
window.bootstrappedUserObject = !{JSON.stringify(bootstrappedUser)}
I've tried this in my html file but it doesn't work:
<script type='text/javascript'>
if (bootstrappedUser != "undefined" ){
window.bootstrappedUserObject = JSON.stringify(bootstrappedUser);
}
</script>
Getting the error: Uncaught ReferenceError: bootstrappedUser is not defined
even though I have created the variable in my backend js file and assigned req.user to it.
I'm suppose to have this file included in my main layout (index.html). The problem is that I'm not using Jade as template engine but plain HTML and I don't know how to transform this code up there to work as simple HTML in my index.html.
It seams that this statement up here only initialise when user hits the login button. Does anyone have any idea or solution how to write the above code in plain HTML.
I browsed StackOverflow and found almost similar problems but not similar enough.
Thanks in advance,
Aleksandar
bootstrappedUser is a variable passed by server-side code to Jade compiler which injects it into the HTML while compiling. If you plan on writing the HTML yourself you can not inject variables from server-side code, obviously because HTML is just a static markup. You'll probably have to get that variable at the client-side from the server yourself via ajax or something.
Via Angular controller let's say ?
You can first define a route on server that serves the variable you want
app.get('/bootstrappedUser', function(req, res){
if(req.user)
res.json(req.user);
else
res.status(401).end();
});
Then on client-side angular you can perform an http request and get that variable
$http.get('/bootstrappedUser')
.success(function(data, status, headers, config) {
$scope.bootstrappedUser = data;
});

include() like function in javascript

objective
I need a function that simply takes all the code from another file and pastes the code in the calling file.
possible solution
a function that works like the include() function in PHP.
reason
When I had hosting, I used the php function include("filename.html") to include things like headers and footers, in all the files on the website. This made life a lot easier!
Now I don't have hosting, because I am working on another site, and I am using Github Pages and thus, I can't use PHP. I need to use only HTML, JS and jQuery etc. So, I need a function that simply takes all the code from another file and pastes the code in the calling file.
Already tried
load() in jQuery.
<pre><script>
$(document).ready(function(){
$("#topbar").load("menubar.html");
});
</script></pre>
This question. I tried the accepted answer, but that didn't work for me.
Kindly help me with this issue.
You should consider setting up a build environment where you can compile your content locally before publishing it. This way, you can organize your code in different files (like in your case, with a header/footer that will always be included with different content files), compile locally to have the files automatically combined into a publish directory, and upload that instead.
This way, instead of e.g. sending 3 requests for a header, content and footer file, the header and footer are pre-compiled into the content file which can then be served with 1 request.
Personally I use Grunt as a build tool for purely static sites, together with a concatenation task (such as grunt-contrib-concat). There are several tutorials on the Grunt website, but you can see an example of how to configure a task for your specific problem here:
https://stackoverflow.com/a/12749861/351435
I do something like that :
var template = {
get: function (url, callback) {
if (this[url]) return callback(null, this[url]);
var self = this;
$.ajax({
"url": url,
"type": "GET"
})
done(function (html) {
self[url] = html;
callback(null, html);
})
.fail(callback);
}
};
after you just need to do that :
template.get("/menu.html", function (err, html, reason) {
if (err) return alert('An error is append : '+reason);
$("#topbar").html(html) // or append
});
I am assuming your scripts run in a browser.
Try the $.getScript function in jQuery.
`$.getMyScript("script.js", function(){
alert("Script executed.");
});`
Depending on how complex you want your solution to get, you could also look at http://requirejs.org/ for incorporating files/scripts/modules.
I believe this question is answered in full on How do I include a JavaScript file in another JavaScript file?.

Categories

Resources