I would like to have a WordPress text widget with a javascript that would populate the widget with text from some .txt file (this is to allow dynamic content on a cached page by allowing me to update that text file with new HTML content).
I found this thread and tried the following code, which did not work:
<script type="text/javascript">
function read(textFile){
var xhr=new XMLHttpRequest;
xhr.open('GET',textFile);
xhr.onload=show;
xhr.send()
}
function show(){
var pre=document.createElement('pre');
pre.textContent=this.response;
document.body.appendChild(pre)
}
read('https://raw.githubusercontent.com/Raynos/file-store/master/temp.txt');
</script>
Any suggestions on how to fix it?
Do you know Javascript or are you just hoping for a copy and paste solution? Perhaps try reworking this code here:
function getStuff(url) {
var xhttp, jsonData, parsedData;
// check that we have access to XMLHttpRequest
if(window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// get the data returned from the request...
jsonData = this.responseText;
// ...and parse it
parsedData = JSON.parse(jsonData);
// return the data here
// if the data you're returning is an object
// you need to know the endpoints
// for example, if there was a username,
// you might return parsedData.username
var something = parsedData.endpoint;
// debug / test
console.log(something);
var elementToShowStuffIn = document.getElementById('theIDOfTheElement');
elementToShowStuffIn.innerHTML = something;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
getStuff('https://raw.githubusercontent.com/Raynos/file-store/master/temp.txt');
Yes, this works. Just replace this line here: var something = parsedData.foo.bar;
Related
I'am trying to parse site. The site (i suppose) using scripts and data bases to load data from (dynamically?). And this is my problem... I am trying to grab data through C# (unfortunately i don't have access to code right now) or JS. And it seems like either C# and JS, get only template of the site, but don't wait until all scripts executed. So this is my question, is there any way to get ALL html source? Maybe call scripts somehow. Or make a request, wait for 10 seconds, and then write source html data into variable?
Here is my JS code.
function request(link)
{
var xhr = new XMLHttpRequest();
xhr.open('GET', link, true);
xhr.onreadystatechange = function() .
{console.log(xhr.readyState);};
xhr.send();
let data = xhr.responseText;
var tempDiv = document.createElement('div');
tempDiv.innerHTML = data.replace(/<script(.|\s)*?\/script>/g,
'');
return tempDiv;
}
function loadFile(url, timeout, callback)
{
var args = Array.prototype.slice.call(arguments, 3);
var xhr = new XMLHttpRequest();
xhr.ontimeout = function () {
console.error("The request for " + url + " timed out.");
};
xhr.onload = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback.apply(xhr, args);
} else {
console.error(xhr.statusText);
}
}
};
xhr.open("GET", url, true);
xhr.timeout = timeout;
xhr.send(null);
let data = xhr.responseText;
return data;
}
function showMessage (message) {
console.log(message + this.responseText);
}
function include(scriptUrl)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", scriptUrl);
xmlhttp.onreadystatechange = function()
{
if ((xmlhttp.status == 200) && (xmlhttp.readyState == 4))
{
eval(xmlhttp.responseText);
}
};
xmlhttp.send();
let data = JSON.parse(xmlhttp.responseText);
var tempDiv = document.createElement('div');
tempDiv.innerHTML = data.replace(/<script(.|\s)*?\/script>/g,
'');
return tempDiv;
}
All this functions do not work as i want.
This isn't really practical - you're trying to load an HTML page, all associated scripts, then run them on the HTML page as if they were in a proper browser environment, but within your current browser session.
This sort of thing is feasible with the jsdom library if you were running on the server-side (NodeJS), because it simulates browser behaviour: https://github.com/jsdom/jsdom. So you could do
JSDOM.fromURL("https://example.com/", { runScripts: "dangerously" }).then(dom => {
console.log(dom.serialize()); //turn the page back into HTML
});
...to get the whole thing.
I'm trying to handle a simple XML file with JS (server-side). So far, with every solution I've tried out, the value shows as "undefined".
I've tried a couple of different approaches, yet I still cannot get past loading the XML file itself and successfully displaying it.
When I've tried to parse it with a DOMParser, the node value is "undefined" (see the present code please).
Another approach I've taken before is to treat it as an XML file without changing it to string beforehand - then I get the '.getElementsByTagName('node')[0]; is not a function' error.
function loadXML(postID){
var xmlhttp = new XMLHttpRequest();
var file = 'logs/queue'+postID+'.xml';
xmlhttp.onreadystatechange = function() {
console.log('[DEBUG]Readystate: '+this.readyState+', status: '+this.status);
if (this.readyState == 4 && this.status ==200) {
myFunction(this);
};
function myFunction(xmlfile) {
var xmlDoc=null;
var data = "";
var parser = new DOMParser();
var user;
xmlDoc = parser.parseFromString(String(xmlfile), "text/xml");
var nodes = xmlDoc.getElementsByTagName("node");
for(i=0; i< nodes.length; i++){
tipper = nodes[i].getAttribute("id");
}
console.log(user)
}
};
xmlhttp.open("GET", file, true);
xmlhttp.send();
}
My only expectation is to obtain the node attribute value of the "node" element.
Instead, I keep getting the "undefined" value as a result.
After two days of struggling with this matter, I finally came up with a working solution.
Therefore, in case somebody was having a problem similar to mine, here goes:
First, I've npm-installed libxmljs. From this point, after quickly checking its wiki page, things went almost silky smooth. The modified code can be analyzed below:
function loadXML(postID){
var xmlhttp = new XMLHttpRequest();
var file = 'file.xml';
xmlhttp.onreadystatechange = function() {
console.log('[DEBUG]Readystate: '+this.readyState+', status: '+this.status);
if (this.readyState == 4 && this.status ==200) {
myFunction(this);
};
}
function myFunction(xmlfile) {
var xmlDoc = libxmljs.parseXml(xmlfile.responseText);
var nodes = xmlDoc.root().childNodes();
var node = nodes[0];
var node_id = xmlDoc.get('//user').attr('id').value();
var uname = xmlDoc.get('//name');
var uamount = xmlDoc.get('//u_amount');
var umessage = xmlDoc.get('//u_message');
console.log('[DEBUG] [id=%s] User: %s. Amount: %s. Message: %s.', node_id, uname.text(), uamount.text(), umessage.text() );
}
xmlhttp.open("GET", file, true);
xmlhttp.send();
};
Here is my javascript function that reads from the file every second and outputs it:
var timer;
var url = "http://.../testdata.txt";
function ajaxcall() {
var lines;
var alltext;
request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState === 4) { // document is ready to parse.
if (request.status === 200) { // file is found
allText = request.responseText;
lines = request.responseText.split("\n");
document.getElementById("test").innerHTML = "";
for (i in lines) {
document.getElementById("test").innerHTML += lines[i] + "<br>";
}
}
}
}
request.send();
}
timer = setInterval(ajaxcall, 1000);
I haven't got the hang of AJAX yet so I tried to make a similar way to write into the file using what I read on the internet:
function chat() {
request = new XMLHttpRequest();
request.open("POST", url, true);
request.send("\n" + document.getElementById("chatbox").value);
}
However that does absolutely nothing and I don't understand why. The element "chatbox" is input type textbox and chat() is called by input type submit.
You cannot write to a file using just a POST call. In fact, you cant write to a file using only JavaScript/AJAX. You will need a server-side script in for example PHP that will write to the file for you, and then you need to call this script using AJAX.
Let's say I have a text file on my web server under /today/changelog-en.txt which stores information about updates to my website. Each section starts with a version number, then a list of the changes.
Because of this, the first line of the file always contains the latest version number, which I'd like to read out using plain JavaScript (no jQuery). Is this possible, and if yes, how?
This should be simple enough using XHR. Something like this would work fine for you:
var XHR = new XMLHttpRequest();
XHR.open("GET", "/today/changelog-en.txt", true);
XHR.send();
XHR.onload = function (){
console.log( XHR.responseText.slice(0, XHR.responseText.indexOf("\n")) );
};
So seeing as the txt file is externally available ie: corresponds to a URL, we can do an XHR/AJAX request to get the data. Note without jQuery, so we'll be writing slightly more verbose vanilla JavaScript.
var xmlHttp;
function GetData( url, callback ) {
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = callback;
xmlHttp.open( "GET", url, true );
xmlHttp.send( null );
}
GetData( "/today/changelog-en.txt" , function() {
if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 {
var result = xmlHttp.responseText;
var allLines = result.split("\n");
// do what you want with the result
// ie: split lines and show the first line
var lineOne = allLines[0];
} else {
// handle the error
}
});
i have a url which returns a json file(i have typed the url in the address bar and it showed the json output) but i don't know how to request for the json file in javascript. can anybody help me?
here's the code:
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=kalutara&format=json&num_of_days=4&key=myKey' ;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
http_request.open('GET', url, true);
http_request.send(null);
http_request.onreadystatechange = function() {
if ( http_request.readyState == 4) {
if ( http_request.status == 200)
success( http_request.responseText);alert(http_request.responseText);
else if (failure)
failure( http_request.status, http_request.statusText);
}
};
Thanks !!
It depends on how you json file looks like.
For e.g.
If the file contains something like
var obj =
{
//Object definition...
}
Then you can just use the regular script tag to be able to use the json object.
If the file in format:
{
//Object Definiton
}
then you can read the contents as defined in your post (Using XMLHTTP request) however then use eval function to make it available in the page something like the one below in your success() method:
eval("var obj = " + http_request.responseText);