Call text file to populate paragraph in HTML - Is it possible? - javascript

Is it possible to call a text file similarily to how you would reference an image in a image tag? Similar to
<img src="http://link.to/image.png">
but
<p src="http://link.to/text.txt"></p>
?
Can you do this with javascript? Any advice would be super appreciated!

You can do this with XHR (XMLHttpRequest) . Pure Javascript:
<p id="text"></p>
<script>
text = document.getElementById('text');
xhr = new XMLHttpRequest();
xhr.open("GET", "http://link.to/file.txt");
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) //the readyState if the status of the request
text.innerHTML = xhr.responseText; // (http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp)
// 4 is a completed request
}
</script>
Or, jQuery has the .load() function:
<p id="text"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$('#text').load('http://link.to/file.txt');
</script>

You can load the remote content via AJAX, as long as the remote server sends you proper CORS headers.
Something like this should work:
var $p = document.getElementsByTagName('p')[0];
var url = $p.getAttribute('src');
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function insertContents() {
if (xhr.readyState === 4 && xhr.status === 200) {
$p.innerHTML = xhr.responseText;
}
};
xhr.open('GET', url);
xhr.send();

possible with ajax
<p data-src="http://link.to/text.txt"></p>
JS:
$('p').each(function () {
var $this = $(this);
$.ajax({
url: $this.data('src'),
dataType: "text",
success: function (data) {
$this.html(data);
}
});
});

var client = new XMLHttpRequest();
client.open('GET', 'text.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();

You can display text file using IFrame. Like this-

Related

Rapidapi Api request with XMLHttpRequest

this is my second post, I hope to be luckier than last time end get some reply. 🙂
I’m trying to make a Rapidapi api request working with javascript ”XMLHttpRequest”
I must say that the api works perfectly with ios siri shortcut.
this is the code provided from apirapit site on the "XMLHttpRequest" section:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://download-video-youtube1.p.rapidapi.com/mp3/medPORJ8KO0");
xhr.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhr.setRequestHeader("x-rapidapi-key", "[my key here]");
xhr.send(data);
And this is my code:
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", url);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "[my key here]");
xhttp.send();
}
</script>
</body>
</html>
Just to testing I created a simply bank html page to have the JSON response beneath the button just after pressing it. The result is just the string “ciao” i set before the this.responseText. If I remove the apikey or modify it with a wrong value an JSON error message appear ( so like the case posted, as I intentionally removed it).
Otherwise as said noting but “ciao” string
Is there any syntax error? Is there a logical reason why it behave like this?
Thanks
Franco
Trying adding a data variable as null. That's what RapidAPI provides in their code snippet.
function loadDoc() {
const data = null
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", URL);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "my key here");
xhttp.send(data);
}

Accessing Vars In All Script Tags In HTML Source Fetched Via xhr Request

How would you access variable values from scripts tags in HTML source of a page fetched via xhr request.
HTML of fetched page...
<html>
<body>
<div id="somecontent"></div>
<script>
var foo="30";
</script>
<script>
var bar="60";
</script>
</body>
</html>
And fetched via xhr request...
var xhr = new XMLHttpRequest();
xhr.open("GET","http://www.example.com/testpage.html");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var html = xhr.responseText;
// try to access var
var result =html.foo+html.bar;
console.log(result);
}
}
xhr.send();
Any ideas would be greatly appreciated!
You can try something like that:
var xhr = new XMLHttpRequest();
xhr.open("GET","http://www.example.com/testpage.html");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var html = xhr.responseText;
var parser = new DOMParser();
var dom = parser.parseFromString(html, 'text/html');
var scripts = dom.querySelectorAll('script');
for (let script of scripts) {
eval(script.innerText);
}
console.log('foo', foo);
console.log('bar', bar);
}
}
xhr.send();

Detect browser tab close without jquery and send some data to php file

I have wrote a script that send some data to an external php file without jquery.
<script type="text/javascript">
var statsPage = 'http://www.my-url.com/response.php';
function ca(c,o,n,t,e,t,u){return p={type:c,userid:o,gender:n}}
ca("pageview", "1", "male");
var params = Object.keys(p).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(p[k])
}).join('&')
const req = new XMLHttpRequest();
//req.addEventListener('load' /*callback after req is complete*/);
req.open('GET', statsPage + '?' + params);
req.send();
req.onreadystatechange = function() {
if (req.readyState == XMLHttpRequest.DONE) {
alert(req.responseText);
}
}
</script>
What i also want to do is to send data when the browser tab is closed, so i wrote a script like below but it is not working. I don't get a response from the php file here.
navigator.sendBeacon = navigator.sendBeacon || function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_title=1');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
};
I found also this script but it gives me also no response from the response.php file as an alert:
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
//console.log(xhr.response);
//console.log(xhr.responseText);
alert(xhr.responseText);
}
}
};
xhr.send(null);
}
EDIT
I did also the following test but now it gives me an alertbox with the value 1 first and then an alert with the response of the function ca (see first part of the code on top for the function). So i think the onbeforeunload is not working here. If i close browser tab i get nothing in response.
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.digital-productions.be/dev/analytics/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.send(null);
}
You can use the beforeunload event to execute code before the user leaves the page, or you could warn them that there is unsaved changes. You can return a message by using e.returnValue = "Message";.
window.addEventListener("beforeunload", function(e) {
//code
});
Here is a link from the mozilla documentation: https://developer.mozilla.org/en/docs/Web/Events/beforeunload

Download file from Dropbox using javascript dropbox api

I tried to download a file from Dropbox using Core Api with javascript.
Here is the method I have written.
function downloadFile(path) {
var url = "https://api-content.dropbox.com/1/files/auto/"+path;
var result;
var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
result = xhr.responseText;
}
}
xhr.send(path);
}
But I am always getting the status as 400. Don't know whats wrong. I got this below HTML as response.
<html>
<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<center>The plain HTTP request was sent to HTTPS port</center>
<hr><center>nginx</center>
</body>
</html>
Edit 1 :
var url = "https://api-content.dropbox.com/1/files/auto/" + path;
var result;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
result = xhr.responseText;
}
}
xhr.open("GET", url, true);
xhr.setRequestHeader("access_token",token);
xhr.send();

Append HTML doc to element using ajax

I've written this code using various online sources but I cannot seem to figure out the last part.
function loadajax (event) {
event.preventDefault();
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200)
document.ajax.dyn="Received:" + xhr.responseText;
else
document.ajax.dyn="Error code " + xhr.status;
}
};
xhr.open('GET', this.href, true);
var content = document.getElementsByTagName('article')[0];
content.innerHTML = xhr.responseText;
}
It seems to work until I need to add content to my page. Indeed content.innerHTML = xhr.responseText; returns nothing. I am getting a simple HTML file, how can I post it in my page? what am I doing wrong?
Thanks for your help!
ajax calls are asynchronous. it will work if you'll move the content.innerHTML = xhr.responseText; line into the onreadystatechange function like this:
function loadajax (event) {
event.preventDefault();
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
document.ajax.dyn="Received:" + xhr.responseText;
content.innerHTML = xhr.responseText;
else
document.ajax.dyn="Error code " + xhr.status;
}
};
xhr.open('GET', this.href, true);
var content = document.getElementsByTagName('article')[0];
}
Put your contet.innerHTML inside status 200 condition.
You are just assigning the value to content before it really exists. Before the ajax got it from server.

Categories

Resources