Using arrays in JavaScript - javascript

I am trying to write a program in javascript in which there is a list of products in an array, and they are sorted in alphabetical order. However, when I enter the code into notepad, and load it up in the website format, it just displays the code I have entered, with no formatting
var products = ["Printer","Tablet","Router","Speakers","Mouse"];
Arrays.sort(products);
System.out.println(Arrays.toString(products));
This is the code exactly as it is in notepad, and in the website bit, it is displayed as one long line of all the programming

You have to surround your code with a script tag:
<script type="text/javascript">Your_code_here</script>
Furthermore System.out.println and Arrays.toString are Java functions. It seems like you have Java confused with JavaScript. I think what you are trying to do is:
<!DOCTYPE html>
<html>
<body>
<script>
var products = ["Printer", "Tablet", "Router", "Speakers", "Mouse"];
products.sort();
var productsString = products.join(" ");
document.write(productsString);
</script>
</body>
</html>

If you point a browser at a URL which returns JavaScript source code, then it will display the JavaScript source code (generally not as a single line those, that suggests a further error in which you are serving it to the browser with a Content-Type: text/html header instead of Content-Type: application/javascript).
If you want to execute client side JavaScript then you need to write an HTML document and import the JavaScript using a <script> element.
Your code will then fail because Arrays and System will be undefined.

Javascript not like java ..to use helper functions in javascript as ..sort,filter,reserve....you can use underscore.js library

Related

How do I save external JSON data to a JavaScript variable? [duplicate]

I have this JSON file I generate in the server I want to make accessible on the client as the page is viewable. Basically what I want to achieve is:
I have the following tag declared in my html document:
<script id="test" type="application/json" src="http://myresources/stuf.json">
The file referred in its source has JSON data. As I've seen, data has been downloaded, just like it happens with the scripts.
Now, how do I access it in Javascript? I've tried accessing the script tag, with and without jQuery, using a multitude of methods to try to get my JSON data, but somehow this doesn't work. Getting its innerHTML would have worked had the json data been written inline in the script. Which it wasn't and isn't what I'm trying to achieve.
Remote JSON Request after page loads is also not an option, in case you want to suggest that.
You can't load JSON like that, sorry.
I know you're thinking "why I can't I just use src here? I've seen stuff like this...":
<script id="myJson" type="application/json">
{
name: 'Foo'
}
</script>
<script type="text/javascript">
$(function() {
var x = JSON.parse($('#myJson').html());
alert(x.name); //Foo
});
</script>
... well to put it simply, that was just the script tag being "abused" as a data holder. You can do that with all sorts of data. For example, a lot of templating engines leverage script tags to hold templates.
You have a short list of options to load your JSON from a remote file:
Use $.get('your.json') or some other such AJAX method.
Write a file that sets a global variable to your json. (seems hokey).
Pull it into an invisible iframe, then scrape the contents of that after it's loaded (I call this "1997 mode")
Consult a voodoo priest.
Final point:
Remote JSON Request after page loads is also not an option, in case you want to suggest that.
... that doesn't make sense. The difference between an AJAX request and a request sent by the browser while processing your <script src=""> is essentially nothing. They'll both be doing a GET on the resource. HTTP doesn't care if it's done because of a script tag or an AJAX call, and neither will your server.
Another solution would be to make use of a server-side scripting language and to simply include json-data inline. Here's an example that uses PHP:
<script id="data" type="application/json"><?php include('stuff.json'); ?></script>
<script>
var jsonData = JSON.parse(document.getElementById('data').textContent)
</script>
The above example uses an extra script tag with type application/json. An even simpler solution is to include the JSON directly into the JavaScript:
<script>var jsonData = <?php include('stuff.json');?>;</script>
The advantage of the solution with the extra tag is that JavaScript code and JSON data are kept separated from each other.
It would appear this is not possible, or at least not supported.
From the HTML5 specification:
When used to include data blocks (as opposed to scripts), the data must be embedded inline, the format of the data must be given using the type attribute, the src attribute must not be specified, and the contents of the script element must conform to the requirements defined for the format used.
While it's not currently possible with the script tag, it is possible with an iframe if it's from the same domain.
<iframe
id="mySpecialId"
src="/my/link/to/some.json"
onload="(()=>{if(!window.jsonData){window.jsonData={}}try{window.jsonData[this.id]=JSON.parse(this.contentWindow.document.body.textContent.trim())}catch(e){console.warn(e)}this.remove();})();"
onerror="((err)=>console.warn(err))();"
style="display: none;"
></iframe>
To use the above, simply replace the id and src attribute with what you need. The id (which we'll assume in this situation is equal to mySpecialId) will be used to store the data in window.jsonData["mySpecialId"].
In other words, for every iframe that has an id and uses the onload script will have that data synchronously loaded into the window.jsonData object under the id specified.
I did this for fun and to show that it's "possible' but I do not recommend that it be used.
Here is an alternative that uses a callback instead.
<script>
function someCallback(data){
/** do something with data */
console.log(data);
}
function jsonOnLoad(callback){
const raw = this.contentWindow.document.body.textContent.trim();
try {
const data = JSON.parse(raw);
/** do something with data */
callback(data);
}catch(e){
console.warn(e.message);
}
this.remove();
}
</script>
<!-- I frame with src pointing to json file on server, onload we apply "this" to have the iframe context, display none as we don't want to show the iframe -->
<iframe src="your/link/to/some.json" onload="jsonOnLoad.apply(this, someCallback)" style="display: none;"></iframe>
Tested in chrome and should work in firefox. Unsure about IE or Safari.
I agree with Ben. You cannot load/import the simple JSON file.
But if you absolutely want to do that and have flexibility to update json file, you can
my-json.js
var myJSON = {
id: "12ws",
name: "smith"
}
index.html
<head>
<script src="my-json.js"></script>
</head>
<body onload="document.getElementById('json-holder').innerHTML = JSON.stringify(myJSON);">
<div id="json-holder"></div>
</body>
place something like this in your script file json-content.js
var mainjson = { your json data}
then call it from script tag
<script src="json-content.js"></script>
then you can use it in next script
<script>
console.log(mainjson)
</script>
Check this answer: https://stackoverflow.com/a/7346598/1764509
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
If you need to load JSON from another domain:
http://en.wikipedia.org/wiki/JSONP
However be aware of potential XSSI attacks:
https://www.scip.ch/en/?labs.20160414
If it's the same domain so just use Ajax.
Another alternative to use the exact json within javascript. As it is Javascript Object Notation you can just create your object directly with the json notation. If you store this in a .js file you can use the object in your application. This was a useful option for me when I had some static json data that I wanted to cache in a file separately from the rest of my app.
//Just hard code json directly within JS
//here I create an object CLC that represents the json!
$scope.CLC = {
"ContentLayouts": [
{
"ContentLayoutID": 1,
"ContentLayoutTitle": "Right",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/right.png",
"ContentLayoutIndex": 0,
"IsDefault": true
},
{
"ContentLayoutID": 2,
"ContentLayoutTitle": "Bottom",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/bottom.png",
"ContentLayoutIndex": 1,
"IsDefault": false
},
{
"ContentLayoutID": 3,
"ContentLayoutTitle": "Top",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/top.png",
"ContentLayoutIndex": 2,
"IsDefault": false
}
]
};
While not being supported, there is an common alternative to get json into javascript. You state that "remote json request" it is not an option but you may want to consider it since it may be the best solution there is.
If the src attribute was supported, it would be doing a remote json request, so I don't see why you would want to avoid that while actively seeking to do it in an almost same fashion.
Solution :
<script>
async function loadJson(){
const res = await fetch('content.json');
const json = await res.json();
}
loadJson();
</script>
Advantages
allows caching, make sure your hosting/server sets that up properly
on chrome, after profiling using the performance tab, I noticed that it has the smallest CPU footprint compared to : inline JS, inline JSON, external JS.

"Refresh" a JavaScript file on change

On my JSP project I've got a .jsp file which contains the following script:
<script type="text/javascript">
$(window).load(function() {
...
options.items = items;
...
});
</script>
The variable items is included in another JavaScript script that is also included in the same .jsp file:
<script type="text/javascript" src="<c:url value="/js/items.js"/>"></script>
items.js has the following structure:
var items = [{...}, {...}, {...}];
Now, the Servlet that implements doGet for this .jsp gathers some data from a database (and this data can be different every time) and uses it to write in the disk the file items.js mentioned above.
The problem is that the server (tomcat7) doesn't see that items.js has changed until it is restarted, but I need to generate that file every time because the data to gather is not always the same. So I'd like to know how to properly provide the first JavaScript function I mentioned with the data on items without having to restart the server. Of course, I want to avoid using scriptlets if possible.
Please note that I can't just delete that piece of JavaScript included in the beginning of this message because that piece of code is using a JavaScript library which I need to use to visualize my data.
Thanks in advance for your help.
Adding a bit modification to your own solution, if you want to avoid scriptlet you can write your above line like this:
instead of
options.items = <%= request.getAttribute("items") %>;
write
options.items = ${requestScope.items}; or options.items = ${items};
I'm replying to my own question to explain how I solved this problem.
I didn't do exactly what Sacho and Christopher Schultz suggested but what they said gave me an idea.
Firstly, on my servlet, I built a StringBuffer containing the data I want. Initially I wanted to use a JSONArray but that would mean using several transformations so that my js script could read (it'd be doable but it wouldn't simply consist of using the standard parser but something a little bit more complex). Then, I added this StringBuffer to the request parameter. This is how it all looks like:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) {
StringBuffer sb = new StringBuffer();
// Fill the StringBuffer
request.setAttribute("items", sb);
request.getRequestDispatcher("/WEB-INF/myjsp.jsp").forward(
request, response);
}
Finally, I accessed this attribute from my jsp file as it follows:
options.items = <%= request.getAttribute("items") %>;
I wanted to avoid scriptlets but I think this piece of code is okay plus it's quite simple to implement.
Thanks for your help!

Output data from TaffyDB

I'm new to JavaScript and am trying to build a script that performs some data management activities(Basically query based data fetching from a database and then displaying it on a webpage).
I generally would do this on the server side with PHP and mysql but my boss want's to see a "sample" before investing in servers etc. (He has no technical knowledge regarding PHP,MySQL etc)
Now without a server I was looking for a way to build a similar system on the client side mostly via javascript. Just to demonstrate the logic I plan on implementing.
For the database part I decided to use TaffyDB, however am having issues getting an output from the database(Display the data on a webpage)
Here's my code
<!DOCTYPE html>
<html>
<head>
<script src="taffydb-master\taffy.js"></script>
<script>
var companies = TAFFY
([
{name:"New York",state:"WA"},
{name:"New Shire",state:"WE"},
{name:"Las Vegas",state:"NV"},
{name:"Boston",state:"MA"}
]);
var cities = new Array();
var cities = companies().select("name");
</script>
</head>
<body>
<script>
document.write = (cities[1]);
</script>
</body>
</html>
I know there's some silly mistake in there but really can't find it. I tried using the developer's tools (Mozilla's default one) but it returns no issues. I basically just get a blank white page when I load this file.
You are using document.write incorrectly. It is a method.
If you change your code to:
<script>
document.write(cities[1]);
</script>
then you will get this output:
New Shire
Also, you should probably wrap the output in some element like so:
<script>
document.write("<p>" + cities[1] + "</p>");
</script>

How to present an XML file in HTML format in different ways, according to user input?

I have an XML file consisting of book nodes, and each book contains 1-4 authors, 1 title & 1 Year
I've also created an XSL file related to the above XML file so that whenever I open the XML file in a browser, its contents are presented in a html table format consisting of 3 rows "Author","Title","Year"
What I want to do now is create an HTML file that will present the above table but not all of its contents, only the ones asked through user input (appropriate fields for user input should be found on that same html file as well I guess..)
e.g. a user can type in the name of an author, or a year, or a title, or a word contained in a title or in an author's name and then have the appropriate table presented to him.
I'm a new to all this so my questions are the following :
Will I have to mess with the content in the XML and XSL files again or should I leave them intact from now on and only deal with the html file I'll be creating?
In order to achieve what I want what should my html file contain? Javascript functions that will be presenting only parts of the XML file but always according to the XSL file? Will I be using XSLT in the html file again or simply javascript?
What I need is to create smth that will take input from the user (javascript?) and then use a parser (XSLT?) to parse through the XML according to the user's input? and then return the result on screen filtered through the XSL template I created??
Could someone please indicate me the process I should follow step by step (not in detail but in which order should I deal with all the issues involved in this..) ?
Thank you very much for your understanding and help! I know there's lots of information on w3schools but the problem is that everything is fragmented and I still don't know how to combine all that, in which order and which method to choose!
btw. I don't want to use jquery for this, only XML,XSLT,XPATH,HTML,Javascript standards..
You need to pass the user-wanted processing as parameter(s) to the transformation.
Read about the xsl:param instruction.
External parameters to the transformation can be any globally declared (children of the top element xsl:stylesheet) xsl:param elements.
The way the invoker of the XSLT transformation specifies the values for these parameters on invoking the transformation is implementation - dependent and varies from one XSLT processor to another. You need to read the documentation of the particular XSLT processor for the exact information how to do this.
For example, if the XSLT processor is the .NET XslCompiledTransform, the way to pass parameters to the transformation is via the XsltArgumentList.AddParam() method.
You need to load the XSL and XML files to the javascript, you can use ajax requests for that, and you can use an iframe to load them for you. Once you have them in javascript you can use XPath and XSLT to do exactly what you want.
For example, here's a simple way to load an xml and then use XPath on it using the iframe way, it uses the input value to query the xml:
<html>
<head>
<title> xml test </title>
<script type="text/javascript">
var xml = null;
function getXml(path) {
document.getElementById("loader").src = path;
}
function loaded(frm) {
if (frm.contentWindow) {
xml = frm.contentWindow.document;
}
}
function query() {
var value = document.getElementById("query").value;
var evaluator = new XPathEvaluator();
var result = evaluator.evaluate("//" + value,
xml,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null);
console.log(result.singleNodeValue);
}
</script>
</head>
<body>
Query the xml: <input type="text" id="query" />
<input type="button" value="Go" onclick="query()" />
<iframe style="width: 0px; height: 0px; display: none;" id="loader" onload="loaded(this)"></iframe>
<script type="text/javascript">
getXml("index.xml");
</script>
</body>
As for the XSLT part, here's a tutorial for how to do that: XSLT - On the Client. In this tutorial they also show how to load the files using ajax.
You can of course load the XSL file just like the XML one in my example.

Using last.fm API in javascript

I have very little experience with web development. I have a little experience with HTML and I am learning JavaScript right now. I created a program in Java using a a last.fm library for Java. I was able to get user information, artist information, and venue information. Now I want to try and do that in a webpage, which is where my problem occurs.
I'm using the javascript last.fm api given here http://github.com/fxb/javascript-last.fm-api
I've downloaded all the .js files and they are in the same directory as my .htm file.
This is my code so far.
<html>
<body>
<script type="text/javascript" src="lastfm.api.md5.js"></script>
<script type="text/javascript" src="lastfm.api.js"></script>
<script type="text/javascript" src="lastfm.api.cache.js"></script>
<script type="text/javascript">
var cache = new LastFMCache();
var lastfm = new LastFM({
apiKey : 'c9946d11aaaaaaaaaaaaaaaaaaaaaaaace',
apiSecret : '9dabf9aaaaaaaaaaaaaaaaxxx11ec3c7a993',
cache : cache
});
lastfm.artist.getInfo({artist: 'The xx'}, {success: function(data){
/* Use Data */
}, error: function(code, message){
/* Show error message. */
}});
</script>
</body>
</html>
I've dug around in the included .js files to try and understand what is going on. So on my initialization of lastfm, I am passing in some objects with associated values, which are then applied to lastfm. If I try and access them through document.write(lastfm.apiKey) I get an undefined value, which I don't really understand.
Also I see that I am calling getInfo and passing in 'The xx' and everything that follows. I don't understand how to use that Data that I believe is returned as a JSON response. How can I print the bio that is associated with that artist?
the code that should go where you have written /* Use Data */ will refer to items such as data.bio. Try alert(data) to see what's in there.
I would also highly recommend using a JavaScript debugging console such as FireBug in order to really see what's going on.
i just used this, and yeah. you just need to console.log(data) in the success to get info about the data that is being passed back from last fm

Categories