I want to read live streaming data from my URL(ie.http://..)
My URL(ie.http://..) contain numeric data and it's continuously growing.
i want to read that data in to my file(HTML5 & javascript).
I have done with static numeric data using AJAX.
But while duing it with dynamic data(live streaming data). i am not able to get responseText().
Is it possible to take responseText() of that URL(ie.http://..) which contain live streaming data?
how i can do this?
My code for reading static data is
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function accessWebservice()
{
var xmlhttp;
xmlhttp = new XMLHttpRequest();
//xmlhttp.open("get","http://192.168.15.174/Streamer/StartStream.aspx?IsTestData=true",true);
//above URL contains live streaming numberic data that i want to read
//But when i am using above URL i am not getting responseText (**How to get it?**)
xmlhttp.open("get","http://localhost/StaticDemoData.txt",true); //This contains static data
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4)
{
if (xmlhttp.status == 200 )
{
var responseData=xmlhttp.responseText;
alert(responseData);
}
else
{
alert("Server returned: " + xmlhttp.status);
}
}
}
xmlhttp.send(null);
}
</script>
</head>
How to get 'xmlhttp.responseText' for live streaming numeric data?
If you check for xmlhttp.readyState == 3 (XMLHttpRequest.LOADING), then accessing xmlhttp.responseText will give you the data that has been received from your server so far. You can then use a setInterval to constantly check xmlhttp.responseText for new data.
Try this script to get stream your data... but you need jquery.js file in your directory and StaticDemoData.txt you can change with other file in .php extension and get your query on the file
<html>
<head>
<script type="text/javascript" src="jquery-1.5.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
userdetails();
});
function userdetails(){
$.post('StaticDemoData.txt',function(data){
$('.result').html(data);
});
setTimeout("userdetails()",1000);
}
</script>
</head>
<body>
<div class="result"></div>
</body>
</html>
Related
On my RPi I have an application (developed in C++) running in the background that does some complex mathematics based on some sensor input and produces some result every second. I want to display this data on a website. So I had the idea to have the application produce a JSON formatted file and read that interactively from a javascript script.
The app now produces a file ModelState.json in my html directory that looks like
{ "x" : -0.886289 , "y" : -0.434931 }
Based on this answer, I wrote the following html/js
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p id="ModelState"></p>
</body>
<script type="text/javascript">
window.onload = function () {
setInterval(showModelState, 1000);
function showModelState() {
readJsonFile("ModelState.json", function(ModelStateJson){
var ModelStateObj = JSON.parse(ModelStateJson);
if (ModelStateObj.x && ModelStateObj.y) {
document.getElementById("ModelState").innerHTML =
"x: " + ModelStateObj.x + ", " +
"y: " + ModelStateObj.y;
}
});
}
function readJsonFile(file, callback) {
let rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status === 200) {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
}
</script>
</html>
However, what I observe is that the file seems to be loaded once. The data on the webpage doesn't change, while the data in the file does change.
I don't know why. Is it that the XMLHttpRequest keeps the file open, such that onreadystatechange is not triggered and the callback function is not called again? I would expect the send response to finish the request, thus close the file.
As cristobal states in the comments, the problem is caused by the browser caching the read file.
One solution is to confuse the browser with a dynamic url, e.g. by changing
readJsonFile("ModelState.json", function(...
to
readJsonFile("ModelState.json?time=${Date.now()}", function(...
An alternative solution (based on this) is that the browser doesn't cache POST http request methods. Thus you can change
rawFile.open("GET", file, true);
to
rawFile.open("POST", file, true);
A third solution (found here) is to add a pragma after the line rawFile.open("GET"...
rawFile.setRequestHeader("Pragma", "no-cache");
More elaborate request headers for cache control can be found here
I am trying to do a simple post from javascript to php, and am not getting data to transfer. I'm using Apache2 on Ubuntu. If I run the php code in Mozilla, it does what I've asked, but when called from javascript php does not seem to get the info to php on the server side. I've tried to simplify the code to focus on just the post function. Here is the html code:
<!doctype html>
<html>
<head>
<title>Post Test </title>
</head>
<body>
<p id="demo"></p>
<script>
var http = new XMLHttpRequest();
var url = "post_test.php";
var file_data = "text string";
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200){
document.getElementById('demo').innerHTML=this.responseText
};
}
http.send(file_data);
</script>
</body>
</html>
Here is the php:
<?php
var_dump(isset($_POST['file_data']));
?>
I get a bool(false) message on the screen.
I checked the file access. Both files are set rwx for all.
I am trying to learn html,javascript, and php. I'd like to hold off on jQuery until I can do more.
You should indicate in the data which field name it should go under. In your case it is file_data.
var myData = "file_data=foo";
http.send(myData);
Then your php
<?php
var_dump(isset($_POST['file_data']));
?>
You are sending PHP a string of plain text. You've made no mention of "file_data" in the string you are sending to the server, so where do you expect PHP to pick up on that name for the key in $_POST? PHP runs on the server, it can't see your JS variable names.
PHP will populate $_POST with data formatted according to the application/x-www-form-urlencoded and multipart/form-data data formats.
You can build application/x-www-form-urlencoded like so:
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var data = "file_data=" + encodeURIComponent(file_data);
http.send(data);
What would be the best way to get the "last modified" attribute from a file NOT on the web server. My purpose is to display the time stamps of specific network files in a web page. All the JavaScript references I have found are for the current file, or from the web server. I have found references for browsing to, drag-and-drop, etc. But I would like to read the file attribute from the original location. Is this even possible??
EDIT:
So now that I have a batch file to create the text file on the web server, how do I get that data into an array so I can display it properly? The data is correct, but it is one long string.
This is my code:
<html>
<head>
<script type="text/javascript">
function getStatus() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("backupStatus").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "file.txt", true);
xhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="getStatus()">Get QNAP Backup Status</button>
<ul id="backupStatus">
</ul>
</body>
</html>
This is my output:
#ECHO 4/13/2016 #FREEMAN1 4/13/2016 #FREEMAN02 4/13/2016 #FREEMAN03 4/7/2016 #FREEMAN4 4/7/2016 #FREEMAN5 4/7/2016 #HR10 4/13/2016 #ACCOUNTING20 4/12/2016 #IT01 4/13/2016 #PROD20 4/12/2016 #UPS10 4/13/2016
javascript can't go out and read files on a user's computer. You'd need to read this information on a server and load it in to the page, or via an ajax call.
I am really new on javascript. I want to read xml from an url and want to parse it on html. I have html and javascript codes like that:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
xmlDoc=loadXMLDoc("http://www.w3schools.com/dom/books.xml");
x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];
document.write(y.nodeValue);
</script>
</body>
</html>
What is wrong ? thanks
This is the standard method to do this task:
Since people keep going along the path of trying to use cross domain for something other than JSONP... IT WILL NOT WORK!
The following code below is an example of what will work, as your server is allowed to get content from other network locations being its more controlled.. Your browser on the other hand can only receive JSONP or PLAIN TEXT... Most google results should explain this as well..
YOUR ONLY OPTION
Is to use a PROXY of some form to obtain what your trying to access, So you only have three choices here.
Use JSONP or Plain Text
Use a Proxy or some other method that is local to your server/website/script/page
Keep trying to use examples posted here after being told cross domain rules apply.
JAVASCRIPT:
function loadXMLDoc(sURL) {
$.post( "myproxy.php", { requrl: sURL }).done(function( data ) {
alert(data);
console.log(data);
document.write(data);
});
}
PHP: myproxy.php
<?php
header('Content-Type: application/xml; charset=utf-8');
$file = file_get_contents($_POST['requrl']);
echo $file;
?>
Please note that is you plan to use this with other types of content then you will need to change/remove the header line.
YOUR BROWSER ALLOWS YOU TO AJAX XML FROM OTHER WEBSITES
If this is the case, then you need to replace or update your web browser..
THE ABOVE SOLUTION IS NOT COMPLEX
This is virtually copy and paste code ready to go, The JS function will return the result/data/content in the three most know ways...
The PHP script is a copy and paste as well.. So if you have PHP installed.
All you would need to do is create a new text file in the same location as your html document and name it as "myproxy.php" and this example will work.
This is a proper XmlHttpRequest with a callback function to handle your XML:
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
function loadXMLDoc(url){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callbackFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function callbackFunction(response){
if (window.DOMParser){ // Non IE
var parser = new DOMParser();
var xml_doc = parser.parseFromString(response,"text/xml");
}else{ // Internet Explorer
var xml_doc = new ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;
xml_doc.loadXML(response);
}
// Do something with your 'xml_doc' object variable here
console.log(xml_doc) // Debugging only.. to see the XML in the browser console for your own reference
var x = xml_doc.getElementsByTagName("title")[0]
var y = x.childNodes[0];
document.write(y.nodeValue);
}
// Call the function to begin code execution
loadXMLDoc('http://www.w3schools.com/dom/books.xml')
</script>
</body>
</html>
This is working code so you can just erase what you have and put this directly in place of it. Good luck!
If you're planning on hosting the file on your own server to access via XHR, the code I offered is intended for that. If w3schools.com had a 'Access-Control-Allow-Origin: *' header on the XML file your are requesting, it would also work. But they don't. So you need to have the XML file in a place where your browser's security will let you access it (same domain origin as your webpage). Otherwise your browser will continue to block the resource with a 'cross-origin-request-blocked' error in the console.
I've been experimenting with Ajast and it's very useful for getting remote URL sources etc. In the below example it bypasses same-domain-policy and gets "Hello World !", but I cannot recreate this when I change it to google.com.
<html>
<head>
<script type="text/javascript" src="http://ajast.org/ajast/ajast.js"></script>
<script id="TestScript" Language="javascript">
function test()
{
var xmlhttp = new AJAST.JsHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4) // 4 = "loaded"
{
if (xmlhttp.status == 200)
document.write(xmlhttp.responseText);
else
alert('ERROR: ' + xmlhttp.status + ' -> ' + xmlhttp.statusText);
}
}
xmlhttp.open("GET", 'http://riffelspot.com/ajast/ajast_full.php', false);
xmlhttp.send();
}
</script>
</head>
<body onload="test();">Please wait...</body>
</html>
</code>
My problem occurs when I change the get url to google.com, can anyone help me? I want JavaScript to fetch the source of a page.
Read the documentation.
AJAST can only be used to send a request to a compatible server-side script.
Basically, it's a non-standard form of JSONP.
I thought that dynamicly loading the script into the DOM would bypass this security feature, like the quote suggests
"The main advantage of AJAST is its ability to make requests to foreign hosts (cross domain) which a standard AJAX request cannot do using a technique known as 'the script tag hack'. "
Where would I be able to find documentation as i dont want to use a JSONP proxy, I would like to request the webpage without signing.