How can I open a JSON file in JavaScript without jQuery? - javascript

I am writing some code in JavaScript. In this code i want to read a json file. This file will be loaded from an URL.
How can I get the contains of this JSON file in an object in JavaScript?
This is for example my JSON file located at ../json/main.json:
{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}
and i want to use it in my table.js file like this:
for (var i in mainStore)
{
document.write('<tr class="columnHeaders">');
document.write('<td >'+ mainStore[i]['vehicle'] + '</td>');
document.write('<td >'+ mainStore[i]['description'] + '</td>');
document.write('</tr>');
}

Here's an example that doesn't require jQuery:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
Call it as:
loadJSON('my-file.json',
function(data) { console.log(data); },
function(xhr) { console.error(xhr); }
);

XHR can be used to open files, but then you're basically making it hard on yourself because jQuery makes this a lot easier for you. $.getJSON() makes this so easy to do. I'd rather want to call a single line than trying to get a whole code block working, but that's up to you...
Why i dont want to use jQuery is because the person i am working for doesn't want it because he is afraid of the speed of the script.
If he can't properly profile native VS jQuery, he shouldn't even be programming native code.
Being afraid means he doesn't know what he is doing. If you plan to go for performance, you actually need to know how to see how to make certain pieces of code faster. If you are only just thinking that jQuery is slow, then you are walking into the wrong roads...

JSON has nothing to do with jQuery.
There is nothing wrong with the code you have now.
To store the variable mainStore, it is a variable in that json.
You should store that json to a variable:
var myJSON = {"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]};
var mainStore = myJSON.mainStore;
//.. rest of your code.

I understand that by "reading a json file" you mean making the request to the url that returns json content. If so, then can you explain why you don't want to use jQuery for this purpose? It has $.ajax function that is perfectly suitable for this and covers the browsers' differences.
If you want to read the file then you have to do it server-side, e.g. php and provide it somehow to the dom (there are different methods) so js can use it. Reading file from disk with js is not possible.

function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText)
}
};
xhttp.open("GET", "./user.json");
xhttp.send();
}
Naming using the linux filename structure
You can store the responseText to a variable or whatever you want to do with it

Related

Writing in another file with javascript

I have a php script (just for calculation) and a html file. Let's say the php file has finished its calculation and the solution is 10. The following line is in the body of the just mentioned html file:
<div id="here"></div>
Now I want the php file to write the 10 into the html. I thought of adding a few lines of javascript at the end of the php to make the job. The question is if this is even possible with something like (index.html).getElementById(here).innerHTML or something. Both files are in the same folder and setting the proper permission shouldn't be a problem.
I know I could put everything in one file but this is part of a bigger project. I just adapted my problem on this simple example to avoid that you need to read plenty of lines.
Your Script should look like this to get response from PHP
<script>
function loadDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("here").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "yourphp.php?q=" + str, true);
xmlhttp.send();
}
</script>
Hope this solves your problem
ref: http://www.w3schools.com/ajax/ajax_php.asp
PHP is server-side and Javascript is client-side. I don't recommend you to use embedded PHP but you should take a look at Ajax Requests.
Here's some documentation

Making an ASP.NET MVC Ajax call with the use of Javascript

First off, thanks for taking the time to read.
I'm trying to delve into ASP.NET MVC at the moment, however i currently have no wish to use any type of JavaScript framework, so please, don't tell me how much easier it would be etc, in your answer.
I currently have a Javascript function that successfully makes an AJAX call, however i am struggling to understand why no values are being returned from the request.
The function is as follows.
function ajaxRequestUser(num) {
var ajax;
try {
ajax = new XMLHttpRequest();
} catch(e) {
try {
ajax = new ActiveXObject(Msxml2.XMLHTTP);
} catch(e){
alert('old browser');
}
}
ajax.readystatechange = function () {
if (ajax.readyState == 4) {
var queryResult = ajax.responseText;
if (!queryResult) {
alert('No Information.');
} else {
alert(queryResult);
}
}
}
var requestString = "?user="+num;
ajax.open("GET", "/Users/GetUser" + requestString, true);
ajax.send(null);
}
The function is called via a separate function that simply does some UI modifications to allow for the display of the data.
The alerts are there at this point, because i was not receiving any data back from the call and i was testing to see if that part of the code was being hit at all (Don't go into the differences between Synchronous and Asynchronous.). No matter how long i waited the data being returned was not being returned, after breaking through the actual server side c#, i saw the data being sent back, but it was just never being received. Is there something in the code that was done wrong? Or am i going about receiving the inbound data in the wrong way?
I have found the issue related to my code, and it is solely an error based around the declaration of my ajax.event where the event is onreadystatechange as opposed to readystatechange

Receiving data from another site

I want to make a little web page which calculates stuff, based on various data from another site. Let's say for an online browser game.
I would like to have it take some specific details from the web pages on the game, but I don't even know where to start.
Is this doable with javascript (if not I would like to know with what language it is)? Could anyone give me a general of guideline of how this can be done?
You can use a combination of AJAX and XMLHTTPRequest, but these are subject to the same origin policy.
Of course, it would make it a lot easier if the external site can send back data in JavaScript Object Notation format (JSON) for readability.
There is a similar question asked here for how to obtain the contents of an external site using XMLHTTPRequest here: How to specify an external website for XMLHTTPRequest
There is another similar question on using XMLHTTPRequest and JSON: Cross-domain JSON request?
I have a standard function for using AJAX to get information dynamically. I use PHP as my listener. Your listener would have to be able to accept variables from the URL, like PHP $_GET[].
In the example below, your listener named "source_url.php" would have to check the values received in $_GET[field] and then simply print/echo the result.
JAVASCRIPT:
function get_(url, func)
{
var http;
try { http = new XMLHttpRequest(); } catch (e) { try { http = new ActiveXObject(\"Msxml2.XMLHTTP\"); } catch (e) { try { http = new ActiveXObject(\"Microsoft.XMLHTTP\"); } catch (e) { alert(\"Your browser broke!\"); return false; } } }
http.open(\"GET\", url, true);
http.onreadystatechange = function() { if(http.readyState == 4) { func(http); } }
http.send(null);
}
function get_info(fieldname)
{
get_("source_url.php?field=" + fieldname, showResult)
}
function showResult(h)
{
alert("The result is: " + h.responseText);
}
HTML
<button onClick='get_info("name");'>Get the ship Name</button>
<button onClick='get_info("reg");'>Get the Registration Number</button>
<button onClick='get_info("capt");'>Who is the Captain?</button>
PHP
<?php
if ($_GET[field] == "name") { print "U.S.S. Enterprise"; }
if ($_GET[field] == "reg") { print "NCC - 1701"; }
if ($_GET[field] == "capt") { print "Jean Luc Picard"; }
?>
I use this all the time, though I have created a more advanced version with authentication security. This is where you should start if you are just learning how AJAX works.

reading server file with javascript

I have a html page using javascript that gives the user the option to read and use his own text files from his PC. But I want to have an example file on the server that the user can open via a click on a button.
I have no idea what is the best way to open a server file. I googled a bit. (I'm new to html and javascript, so maybe my understanding of the following is incorrect!). I found that javascript is client based and it is not very straightforward to open a server file. It looks like it is easiest to use an iframe (?).
So I'm trying (first test is simply to open it onload of the webpage) the following. With kgr.bss on the same directory on the server as my html page:
<IFRAME SRC="kgr.bss" ID="myframe" onLoad="readFile();"> </IFRAME>
and (with file_inhoud, lines defined elsewhere)
function readFile() {
func="readFile=";
debug2("0");
var x=document.getElementById("myframe");
debug2("1");
var doc = x.contentDocument ? x.contentDocument : (x.contentWindow.document || x.document);
debug2("1a"+doc);
var file_inhoud=doc.document.body;
debug2("2:");
lines = file_inhoud.split("\n");
debug2("3");
fileloaded();
debug2("4");
}
Debug function shows:
readFile=0//readFile=1//readFile=1a[object HTMLDocument]//
So statement that stops the program is:
var file_inhoud=doc.document.body;
What is wrong? What is correct (or best) way to read this file?
Note: I see that the file is read and displayed in the frame.
Thanks!
Your best bet, since the file is on your server is to retrieve it via "ajax". This stands for Asynchronous JavaScript And XML, but the XML part is completely optional, it can be used with all sorts of content types (including plain text). (For that matter, the asynchronous part is optional as well, but it's best to stick with that.)
Here's a basic example of requesting text file data using ajax:
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
You'd call that like this:
getFileFromServer("path/to/file", function(text) {
if (text === null) {
// An error occurred
}
else {
// `text` is the file text
}
});
However, the above is somewhat simplified. It would work with modern browsers, but not some older ones, where you have to work around some issues.
Update: You said in a comment below that you're using jQuery. If so, you can use its ajax function and get the benefit of jQuery's workarounds for some browser inconsistencies:
$.ajax({
type: "GET",
url: "path/to/file",
success: function(text) {
// `text` is the file text
},
error: function() {
// An error occurred
}
});
Side note:
I found that javascript is client based...
No. This is a myth. JavaScript is just a programming language. It can be used in browsers, on servers, on your workstation, etc. In fact, JavaScript was originally developed for server-side use.
These days, the most common use (and your use-case) is indeed in web browsers, client-side, but JavaScript is not limited to the client in the general case. And it's having a major resurgence on the server and elsewhere, in fact.
The usual way to retrieve a text file (or any other server side resource) is to use AJAX. Here is an example of how you could alert the contents of a text file:
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){alert(xhr.responseText);};
xhr.open("GET","kgr.bss"); //assuming kgr.bss is plaintext
xhr.send();
The problem with your ultimate goal however is that it has traditionally not been possible to use javascript to access the client file system. However, the new HTML5 file API is changing this. You can read up on it here.

How to read a text file from server using JavaScript?

On the server, there is a text file. Using JavaScript on the client, I want to be able to read this file and process it. The format of the file on the server cannot be changed.
How can I get the contents of the file into JavaScript variables, so I can do this processing? The size of the file can be up to 3.5 MB, but it could easily be processed in chunks of, say, 100 lines (1 line is 50-100 chars).
None of the contents of the file should be visible to the user; he will see the results of the processing of the data in the file.
You can use hidden frame, load the file in there and parse its contents.
HTML:
<iframe id="frmFile" src="test.txt" onload="LoadFile();" style="display: none;"></iframe>
JavaScript:
<script type="text/javascript">
function LoadFile() {
var oFrame = document.getElementById("frmFile");
var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML;
while (strRawContents.indexOf("\r") >= 0)
strRawContents = strRawContents.replace("\r", "");
var arrLines = strRawContents.split("\n");
alert("File " + oFrame.src + " has " + arrLines.length + " lines");
for (var i = 0; i < arrLines.length; i++) {
var curLine = arrLines[i];
alert("Line #" + (i + 1) + " is: '" + curLine + "'");
}
}
</script>
Note: in order for this to work in Chrome browser, you should start it with the --allow-file-access-from-files flag. credit.
Loading that giant blob of data is not a great plan, but if you must, here's the outline of how you might do it using jQuery's $.ajax() function.
<html><head>
<script src="jquery.js"></script>
<script>
getTxt = function (){
$.ajax({
url:'text.txt',
success: function (data){
//parse your data here
//you can split into lines using data.split('\n')
//an use regex functions to effectively parse it
}
});
}
</script>
</head><body>
<button type="button" id="btnGetTxt" onclick="getTxt()">Get Text</button>
</body></html>
You need to use Ajax, which is basically sending a request to the server, then getting a JSON object, which you convert to a JavaScript object.
Check this:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
If you are using jQuery library, it can be even easier:
http://api.jquery.com/jQuery.ajax/
Having said this, I highly recommend you don't download a file of 3.5MB into JS! It is not a good idea. Do the processing on your server, then return the data after processing. Then if you want to get a new data, send a new Ajax request, process the request on server, then return the new data.
Hope that helps.
I used Rafid's suggestion of using AJAX.
This worked for me:
var url = "http://www.example.com/file.json";
var jsonFile = new XMLHttpRequest();
jsonFile.open("GET",url,true);
jsonFile.send();
jsonFile.onreadystatechange = function() {
if (jsonFile.readyState== 4 && jsonFile.status == 200) {
document.getElementById("id-of-element").innerHTML = jsonFile.responseText;
}
}
I basically(almost literally) copied this code from http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get2 so credit to them for everything.
I dont have much knowledge of how this works but you don't have to know how your brakes work to use them ;)
Hope this helps!
It looks like XMLHttpRequest has been replaced by the Fetch API. Google published a good introduction that includes this example doing what you want:
fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
However, you probably want to call response.text() instead of response.json().
Just a small point, I see some of the answers using innerhtml. I have toyed with a similar idea but decided not too, In the latest version react version the same process is now called dangerouslyinnerhtml, as you are giving your client a way into your OS by presenting html in the app. This could lead to various attacks as well as SQL injection attempts
You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status and if it is from web server it returns the status)
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
For device file readuing use this:
readTextFile("file:///C:/your/path/to/file.txt");
For file reading from server use:
readTextFile("http://test/file.txt");
I really think your going about this in the wrong manner. Trying to download and parse a +3Mb text file is complete insanity. Why not parse the file on the server side, storing the results viva an ORM to a database(your choice, SQL is good but it also depends on the content key-value data works better on something like CouchDB) then use ajax to parse data on the client end.
Plus, an even better idea would to skip the text file entirely for even better performance if at all possible.

Categories