Tried this code to read data from a local text file.
But I don't know why this is not working.
Could someone help me with this problem. I can see in most of the answers in stackoverflow, they say that this is working, but this is not working for me. do I have to install anything for this?
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","sample.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>
The problem is that XMLHttpRequest will not read files from the local filesystem (otherwise malicious websites could read files on your desktop!). Here are some solutions:
Install a server on 127.0.0.1. For a quick and dirty solution, you can use Python's SimpleHTTPServer or the Node.js http-server package. For production, use Nginx or Apache.
Put your files on a web host, such as Github Pages.
You can only read local files on the server side without user interaction. If you want to read a client side file, you have to use an html interaction element like:
<input type="file" id="openselect" />
Otherwise, if your file is on the server side, you could use something like:
function getdatafromfile(filename) {
// Read annotation file. Example : %timeinstant \t %value \n
// Return an array of string
var arraydata
$.ajax({
type: "GET",
url: filename,
dataType: "text",
success: function(csv) {arraydata = $.csv.toArrays(csv,{separator:'\t'}); }
});
return arraydata;}
Related
I'm comfortable working with $.ajax and also in using cache.manifest. Recently I decided to start using "get" instead of "post" to help see the parameters easier.
In this proof-of-concept, if I delete the cache.manifest from the server, everything works. But when I put the cache.manifest on the server, the page stops working with an undefined jqXHR.responseText.
Furthermore, if I change the get to a post, it works with the cache.manifest.
Q: Does an https require a post, making "get" invalid if you are using a cache manifest? It seems to be working if the cache manifest is missing and it works with the cache manifest if I use post.
var local = {}
local.type = 'get'
local.dataType = 'text'
local.data = {}
local.data.CtrlName = 'testing123'
var promise = $.ajax('where_ctrlName.cfm',local)
promise.done(done)
promise.fail(fail)
function done(response) {
console.log(response)
}
function fail(jqXHR, textStatus, errorThrown) {
debugger
}
window.applicationCache.addEventListener('updateready', updateReady, false)
function updateReady() {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
$('body').html('<h1>Updating</h1>')
setTimeout(reloadCache,1000)
}
}
function reloadCache() {
window.location.reload()
}
<html manifest="cache.manifest">
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
Here's my cache.manifest:
CACHE MANIFEST
https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
For What It's Worth, this is an https call.
How do I write a script to permanently change a static html file after making an ajax call to the node.js server? Any examples would be greatly appreciated :)
I agree with NikxDa that this is probably not the best solution for you, but this code should do the trick.
/write.js
var http = require('http');
var fs = require('fs');
var url = require('url');
//Lets define a port we want to listen to
const PORT=8080;
function handleRequest(request, response){
var path = url.parse(request.url).pathname;
if(path=="/write"){
fs.appendFile('message.html', 'Node.js!', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
} else {
fs.readFile('index.html',function (err, data){
response.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
response.write(data);
response.end();
});
}
}
// Create a server.
var server = http.createServer(handleRequest);
server.listen(PORT, function(){
console.log("Server listening on: http://localhost:%s", PORT);
});
/index.html
<!DOCTYPE html>
<head>
<script>
function writeIt()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:8080/write", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
string=xmlhttp.responseText;
document.write(string + ": Saved change to message.html");
}
}
xmlhttp.send();
}
</script>
</head>
<body>
<p>Click the button to send an AJAX request to `write.js`<p>
<br><button onclick="writeIt()">Click Me</button>
</body>
/message.html
Node.js!
Editing the file directly via node would probably be really bad, I do not even know if it is at all possible. I think the better solution is for your Node Server to make the data you want to change accessible and then use jQuery or Angular to update the HTML-File when it is actually loaded.
Another approach would be to use a templating engine like https://github.com/tj/ejs, and then serve the file via Node directly, so you can change the data in the Node-Application itself every time.
I'm actually working on a little application. I have one server written in C which is listening on the port 5260. In the other side I have a NodeJS client which is listening on the port 7777. A HTML page can be reach via this port. In the HTML page I have a simple button.
When I click on this one a message is sent to my NodeJS server and is written on the terminal. Now I would like to fetch this command and send it to my C server which is still running and waiting for a request.
My client.js :
var http = require('http');
var ejs = require('ejs');
var express=require('express');
var app = express();
app.engine('html', ejs.renderFile);
app.set('/', __dirname);
app.get('/', function(request,response) {
response.render('index.ejs.html');
})
var options = {
host: '192.168.1.154',
path: '/',
port: '5260',
method: 'POST'
};
app.post('/play', function(req, res){
var res = http.request(options);
console.log("START_BG;BG1\n");
});
app.listen(7777);
And my HTML file :
<html>
<head>
<script type="text/javascript" src="client.js"></script>
<script type="text/javascript">
function sendMessage() {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/play', true);
xhr.onload = function() {
console.log(xhr);
};
xhr.send();
}
</script>
</head>
<body>
<button onclick="sendMessage()">VIDEO</button>
</body>
</html>
Well. I see some strange things in your code
1 You're making the post request to 192.168.1.254:5620/play without sending any data on it
2 You're not waiting fro the request to end and blindly print on your console without checking the result. Don't know if its the desired behaviour, but it seems a bit strange
Without more knowledge about the scenario is difficult to suggest an idea.
What is the answer you expect from the remote server?
It's suposed to print something in the (remote) console ?
What it should return via HTTP ?
Anyway I suggest you correct your code as follows:
app.post('/play', function(req, res){
var res = http.request(options, function(response){
// do any checking about response status and/or body if any
console.log("START_BG;BG1\n");
});
});
We are using Cordova 3.4.0 to develop an app. Everything works fine on Android and iOS and also if we launch our app in a desktop browser. But we are stuck with really strange issue on Windows Phone 8.1.
Here is a simplified code example to test.
index.html in the application root:
<!DOCTYPE html>
<html>
<head>
<title>Mobile sandbox</title>
<meta charset="UTF-8">
<script type="text/javascript" src="libs/jquery/jquery.min.js"></script>
</head>
<body>
<div id="redbox" style="width:100px;height:100px;background-color:red;">
</div>
<div id="greenbox" style="width:100px;height:100px;background-color:green;">
</div>
<script>
$(function () {
alert("Requesting data for redbox...");
$.ajax("test/redText.html")
.done(function (text) {
alert("Filling redbox with contents " + text);
$("#redbox").html(text);
})
.fail(function () {
alert("Error in redbox");
})
.always(function () {
alert("Complete redbox");
});
alert("Requesting data for greenbox...");
$.ajax("test/greenText.html")
.done(function (text) {
alert("Filling greenbox with contents " + text);
$("#greenbox").html(text);
})
.fail(function () {
alert("Error in greenbox");
})
.always(function () {
alert("Complete greenbox");
});
});
</script>
</body>
</html>
test/greenText.html:
<span>GREEN</span>
test/redText.html:
<span>RED</span>
The only dependency to run this test is jQuery which we have put in libs/jquery/ folder.
Now, if we run this code in every desktop browser and in iOS and Android, no matter if from local folder (with browser flags for local AJAX) or from server, we get the right sequence of alerts and AJAX loads correct data in appropriate boxes:
Requesting data for redbox...
Requesting data for greenbox...
Filling redbox with contents <span>RED</span>
Complete redbox
Filling greenbox with contents <span>GREEN</span>
Complete greenbox
We get the same result if we run the index.html on Windows Phone through its Internet Explorer.
But when we deploy the same code to Windows Phone as Cordova app, strange thing happens. The redbox request never receives any data, nor any errors. The greenbox request receives data of redbox, and thus we have empty red box and green box with text "RED" in it.
Here is the sequence of alerts:
Requesting data for redbox...
Requesting data for greenbox...
Filling greenbox with contents <span>RED</span>
Complete greenbox
What's going on there, why one AJAX request does not return and the other receives wrong response? How do we fix it?
EDIT 1:
Our nest step will be to find out if it's Cordova specific issue (I see there is some XHRHelper object in the Corodva WP8 template) or it's Microsoft's phone:WebBrowser fault.
EDIT 2:
It seems, WebBrowser itself does not support AJAX requests to local files (I got "Access denied") and that's why Cordova invented XHRHelper class. But I found a related bugreport which they closed as "Cannot reproduce":
https://issues.apache.org/jira/browse/CB-4873
Is there any Cordova developer here who could suggest a fix for XHRHelper, so it supports multiple sequential AJAX requests?
Again, I cannot reproduce your results. I quickly put together a version which I will post to the JIRA issue: https://issues.apache.org/jira/browse/CB-4873
Requesting data for redbox...
Requesting data for greenbox...
Filling redbox with contents
<span>REd</span>
Complete redbox
Filling greenbox with contents
<span>GREEN</span>
Complete greenbox
I modified your source a little just to make sure there were no issues with alert interfering ...
var eventLog = [];
var oneDone = false;
$(function () {
eventLog.push("Requesting data for redbox...");
$.ajax("redText.html")
.done(function (text) {
eventLog.push("Filling redbox with contents " + text);
$("#redbox").html(text);
})
.fail(function (e) {
eventLog.push("Error in redbox" + JSON.stringify(e));
})
.always(function () {
eventLog.push("Complete redbox");
if (oneDone) {
console.log(eventLog.join("\n"));
alert(eventLog.join("\n"));
}
else {
oneDone = true;
}
});
eventLog.push("Requesting data for greenbox...");
$.ajax("greenText.html")
.done(function (text) {
eventLog.push("Filling greenbox with contents " + text);
$("#greenbox").html(text);
})
.fail(function () {
eventLog.push("Error in greenbox");
})
.always(function () {
eventLog.push("Complete greenbox");
if (oneDone) {
console.log(eventLog.join("\n"));
alert(eventLog.join("\n"));
}
else {
oneDone = true;
}
});
});
I need a very basic, simple and lightweight AJAX script.
Does anyone have a shell of such a script they can share?
Here's what I have:
I have a PHP script on the server that echo's the current date and time on the server
I just need the javascript that calls the php script and loads the echoed text string into a js var so I can use it in my app
(the reason I need the server's clock is that all visitors to the site have to work off the same clock. The app does not work for visitors outside the server's timezone.)
Thanks for helping out.
JQuery is perhaps the right answer for AJAX but you can also do this in plain old Javascript as follows:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc(){
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//the callback function to be callled when AJAX request comes back
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","<<url of web address>>",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
You can find a simple example here:
AjaxCall = function(Data, WebServiceURL, Callback) {
var request;
var url = WebServiceURL;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
Callback(request);
} else {
alert("Sorry, an error occurred. " + request.responseText);
}
}
};
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(Data);
} else if (window.ActiveXObject) {
url += "?" + Data;
request = new ActiveXObject("Microsoft.XMLHTTP");
if (request) {
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
Callback(request);
} else {
alert("Sorry, an error occurred. " + request.responseText);
}
}
};
request.open("GET", url, true);
request.send();
}
}
};
The the ajax functionality in jQuery is great but does mean a greater page download for one simple Javascript function.
You can find a downloadable fully worked example on my blog here:
http://www.willporter.co.uk/blog/simple-ajax-script.aspx
It uses ASP.NET on the server side but you should get the idea.
jQuery has made very simple ajax methods for you to use. You can find more information about them here.
Sample:
$.ajax({
type: 'GET',
url: '/SomeUrl/On/The/Server',
data: { SomeValue: 10 },
success: function(data, status)
{
// On Success
},
error: function(data, status)
{
// On Error
}
});
Look into this maybe : http://www.scriptiny.com/2011/01/simple-ajax-function-example/
jQuery is a more reliable library overall, but the lightest-weight AJAX methods I have found are the extremely simple Feather AJAX, coming in at 1.6 KB (with room for compression), or a one-liner snippet that I can't guarantee.
The risk of extremely lightweight libraries is that if they break, you're relying on the owner to fix it instead of a team of developers.
An alternative approach to solving your problem is to based your times on UTC instead of server-local time. You can even show the client local times based on that utc time, with a little work.
May I suggest AJAX Generator?
I am developer, and it is commercial tool but it has demo as well.
What you could do with that tool is:
put annotation on your PHP function
run AJAX Generator on PHP source file
include generated JavaScript file in HTML page and use PHP service as if you were calling function
To make it more clear, here is example code:
//example.php
<?php
//#WebService
function getServerDate(){
return date('m/d/Y h:i:s a', time());
}
?>
Now run generator on: example.php
Output would be two files: example_service.php and example_caller.js
Now you need to:
add example_service.php in same directory where is example.php and
include example_caller.js in index.html
Sorry for posting image instead of HTML code, but it wasn't showing properly.