Does anyone know of a tutorial on how to read data from a server side file with JS? I cant seem to find any topics on this when I google it. I tried to use but it does not seem to work. I just want to read some data from a file to display on the page. Is this even possible?
var CSVfile = new File("test.csv");
var result = CVSfile.open("r");
var test = result.readln();
To achieve this, you would have to retrieve the file from the server using a method called AJAX.
I'd look into JavaScript libraries such as Mootools and jQuery. They make AJAX very simple use.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.min.js"></script>
<script type="text/javascript">
//This event is called when the DOM is fully loaded
window.addEvent("domready",function(){
//Creating a new AJAX request that will request 'test.csv' from the current directory
var csvRequest = new Request({
url:"test.csv",
onSuccess:function(response){
//The response text is available in the 'response' variable
//Set the value of the textarea with the id 'csvResponse' to the response
$("csvResponse").value = response;
}
}).send(); //Don't forget to send our request!
});
</script>
</head>
<body>
<textarea rows="5" cols="25" id="csvResponse"></textarea>
</body>
</html>
If you upload that to the directory that test.csv resides in on your webserver and load the page, you should see the contents of test.csv appear in the textarea defined.
You need to use AJAX. With jQuery library the code can look like this:
$.ajax({ url: "test.csv", success: function(file_content) {
console.log(file_content);
}
});
or if you don't want to use libraries use raw XMLHTTPRequest object (but you I has different names on different browsers
function xhr(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();
} catch(e) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
req = xhr();
req.open("GET", "test.cvs");
req.onreadystatechange = function() {
console.log(req.responseText);
};
req.send(null);
UPDATE 2017 there is new fetch api, you can use it like this:
fetch('test.csv').then(function(response) {
if (response.status !== 200) {
throw response.status;
}
return response.text();
}).then(function(file_content) {
console.log(file_content);
}).catch(function(status) {
console.log('Error ' + status);
});
the support is pretty good if you need to support browser that don't support fetch API you can use polyfill that github created
Related
Very often it is necessary to load contents from files that are stored in server into a Javascript variable or display it in a HTML element in order to accomplish some task inside a webpage.
How can I do that without relying in JQuery?
One of the easiest ways I have found of doing that is by creating a function that gets a file and call's back another function when the download is ready.
So in the example below, when the "test.txt" file content is loaded, it is displayed in a pre element.
<html>
<body>
<pre id="output"></pre>
</body>
<script type="text/javascript">
function get_file(url, callback)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
callback(xmlhttp.responseText);
}
}
xmlhttp.send();
}
get_file("test.txt", function(response)
{
document.getElementById("output").innerHTML=response;
});
</script>
</html>
IMPORTANT
If you want to make your XMLHttpRequest synchronous, just change the line
xmlhttp.open("GET", url, true);
To
xmlhttp.open("GET", url, false);
But it will come at the expense of hanging your webpage until the data is loaded.
Try using fetch:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
It's much easier to use than XMLHttpRequest.
Then, once you've fetched the resource, use insertAdjacentHtml to add it to the document body: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
i.e.
fetch("test.json")
.then(function(response) {
return response.json();
})
.then(function(json) {
document.body.insertAdjacentHtml("afterbegin", "<p>" + json + "</p>);
});
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
});
Trying to implement the simplest server-client on my PC.
The argv part is because I'm debugging it in VS and it started as an application. It works as a standalone app and I want to make it a server. If I enter
http://localhost:8080/
in the browser I can see in the node.exe window that the server runs properly. But when I run the html with the script nothing happens (I get no response, although no error either, and the server doesn't get the request)
If anyone could help I would appreciate it.
Client:
<html>
<body>
<script type = "text/javascript">
<!--
//Browser Support Code
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
document.myForm.response.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "http://localhost:8080", true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
<button onclick="ajaxFunction()">request</button> <br />
<input type='text' name='response' />
</form>
</body>
</html>
Server:
var fs = require("fs"),
my_http = require("http"),
sys = require("sys");
my_http.createServer(function(request,response){
fs.readFile(process.argv[2], 'utf8', function(err, data) {
if (err) {
console.log("FILE READ ERROR: ", err);
process.exit();
}
response.writeHeader(200, {"Content-Type": "text/plain"});
response.write("message");
response.end();
});
}).listen(8080);
sys.puts("Server Running on 8080");
EDIT:
Well, I made some progress you could say, but I don't like not knowing what the problem is. I created a new TypeScript project in VS and put my ajaxFunction in it and the button\textbox as in the initial html file. Now the server does get the request but it doesn't seem to call the callback function onreadystatechange.
The new client code:
default.htm:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>TypeScript HTML App</title>
<link rel="stylesheet" href="app.css" type="text/css" />
<script src="app.js"></script>
</head>
<body>
<h1>TypeScript HTML App</h1>
<div id="content"></div>
<button onclick="ajaxFunction()">request</button> <br />
<input type='text' name='response' />
</body>
</html>
app.ts: (it's in js though)
var response;
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
var response;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
response.innerHTML = "hi";
}
}
ajaxRequest.open("GET", "http://localhost:8080", true);
ajaxRequest.send(null);
}
window.onload = () => {
response = document.getElementById('content');
};
I am now getting a "Cancelled" network request in Chrome's dev tools.
New answer:
What do you get if you log some values out in your onreadystatechange handler?
ajaxRequest.onreadystatechange = function () {
console.log('ajaxRequest.readyState=', ajaxRequest.readyState, ajaxRequest.status);
if (ajaxRequest.readyState == 4) {
document.myForm.response.value = ajaxRequest.responseText;
}
}
Original answer:
There are a couple of possibilities that might be occurring.
Your ajaxRequest variable is local to the ajaxFunction() and might be getting garbage collected after the function is executed.
Try moving the ajaxRequest outside ajaxFunction() like this:
var ajaxRequest; // The variable that makes Ajax possible!
function ajaxFunction() {
... rest of your client code.
}
That way the variable will still be in scope after the function has been invoked.
Alternatively, you might be running into a cross-domain security issue if your client is running on a different domain to your server (e.g. http://localhost:8081/ vs http://localhost:8080/).
Can you check if the browser is actually making the request (i.e. check with the browser's development tools and not on the server)? There should be a 'network' tab in the development tools for whichever browser you are using.
Have a look at the documentation for CORS (Cross-Origin Resource Sharing) to get an idea of what might be happening.
Edit: Here's a nice overview of cross-domain security errors and how to address it in a standard Node.js server: http://bannockburn.io/2013/09/cross-origin-resource-sharing-cors-with-a-node-js-express-js-and-sencha-touch-app/
This answer shows how to add the headers in a Connect server:
How can I add CORS-Headers to a static connect server?
I am trying to consume the weather web service provided by wsf.cdyne.com/WeatherWS/Weather.asmx. I am sure that I can get a response in XML format by using the uri " 'http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?ZIP=' + zipcode".
So what I want to do now is sending the uri above using XmlHttpRequest. I added some alerts to monitor the status. After open() the readyState is 1. After that I can't get any other response. If I remove the statement "xmlHttpRequest.onreadystatechange = processRequest;", I cannot see any response after send(). So I just hope someone can help me to check what is wrong.
<html>
<head>
<title>weather app</title>
</head>
<body>
<script language="JavaScript">
function httpGet()
{
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
if (xmlHttp.overrideMimeType)
xmlHttp.overrideMimeType('text/xml');
}
else if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
xmlHttp.open( "GET", "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?ZIP=85281", false );
alert("1 " +xmlHttp.readyState);
xmlHttpRequest.onreadystatechange = processRequest;
alert("2 " +xmlHttp.readyState);
xmlHttp.send();
alert("3 " +xmlHttp.readyState);
document.write(xmlHttp.responseText);
return xmlHttp.responseText;
}
httpGet();
</script>
</body>
</html>
As correctly stated by #robertklep this request is cross-domain. Browsers disallow cross-browser requests as a security measure so you don't hijack the user's sessions on their sites etc.
To get it to work you can create a proxy on the local site. If the site offers support to use JSONP cross-domain, you could use that.
For more information lookup some information on cross-domain policies or if they have some API docs, they may have information there on your problem too.
I am trying to get the source code of HTML by using an XMLHttpRequest with a URL. How can I do that?
I am new to programming and I am not too sure how can I do it without jQuery.
Use jQuery:
$.ajax({ url: 'your-url', success: function(data) { alert(data); } });
This data is your HTML.
Without jQuery (just JavaScript):
function makeHttpObject() {
try {return new XMLHttpRequest();}
catch (error) {}
try {return new ActiveXObject("Msxml2.XMLHTTP");}
catch (error) {}
try {return new ActiveXObject("Microsoft.XMLHTTP");}
catch (error) {}
throw new Error("Could not create HTTP request object.");
}
var request = makeHttpObject();
request.open("GET", "your_url", true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4)
alert(request.responseText);
};
You can use fetch to do that:
fetch('some_url')
.then(function (response) {
switch (response.status) {
// status "OK"
case 200:
return response.text();
// status "Not Found"
case 404:
throw response;
}
})
.then(function (template) {
console.log(template);
})
.catch(function (response) {
// "Not Found"
console.log(response.statusText);
});
Asynchronous with arrow function version:
(async () => {
var response = await fetch('some_url');
switch (response.status) {
// status "OK"
case 200:
var template = await response.text();
console.log(template);
break;
// status "Not Found"
case 404:
console.log('Not Found');
break;
}
})();
There is a tutorial on how to use Ajax here: https://www.w3schools.com/xml/ajax_intro.asp
This is an example code taken from that tutorial:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// Code for Internet Explorer 7+, Firefox, Chrome, Opera, and Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// Code for Internet Explorer 6 and Internet Explorer 5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
I had problems with the fetch api and it seams that it always returns promise even when it returns text "return await response.text();" and to handle that promise with the text, it needs to be handled in async method by using .then.
<script>
// Getting the HTML
async function FetchHtml()
{
let response = await fetch('https://address.com');
return await response.text(); // Returns it as Promise
}
// Usaing the HTML
async function Do()
{
let html = await FetchHtml().then(text => {return text}); // Get html from the promise
alert(html);
}
// Exe
Do();
</script>
For an external (cross-site) solution, you can use: Get contents of a link tag with JavaScript - not CSS
It uses $.ajax() function, so it includes jquery.
First, you must know that you will never be able to get the source code of a page that is not on the same domain as your page in javascript. (See http://en.wikipedia.org/wiki/Same_origin_policy).
In PHP, this is how you do it:
file_get_contents($theUrl);
In javascript, there is three ways :
Firstly, by XMLHttpRequest : http://jsfiddle.net/635YY/1/
var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);
Secondly, by iFrames : http://jsfiddle.net/XYjuX/1/
var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);
Thirdly, by jQuery : [http://jsfiddle.net/edggD/2/
$.get('../edggD',function(data)//Remember, same domain
{
alert(data);
});
]4
Edit: doesnt work yet...
Add this to your JS:
var src = fetch('https://page.com')
It saves the source of page.com to variable 'src'
I'm trying to use an ajax request to connect, and gather data from, a PHP file. THe AJAX JS is on a different website than the PHP, just an FYI.
Here is the JS:
var quer;
try
{
quer = new XMLHttpRequest();//I'm running in safari, so this gets called.
}
catch (e)
{
try
{
quer = new ActiveXObject("Msxml2.XMLHttp");
}
catch (e)
{
try
{
quer = new ActiveXObject("Microsoft.XMLHttp");
}
catch (e)
{
return false;
}
}
}
quer.onreadystatechange = function(){
if (quer.readyState == 4)//Good to go.
{
var resp = quer.responseText;
alert(resp);
}
}
quer.open("POST", "(blanked URL for security reasons)", true);
quer.send(null);
Resp is always, and I mean ALWAYS blank. Can anyone offer any help?
THe AJAX JS is on a different website
than the PHP
There is your problem. You can't do an XMLHttp request from a different domain.
You can read more about the same origin policy.
You cannot make AJAX requests to scripts that reside on other domains. It is a violation of the same origin policy.