How to Read Files with XMLHttpRequest in JS - javascript

How would I do that? My file is called ajax_info.txt and my response should be a self-called [handler] function.

You would do this with the following code:
const xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
(function(){
document.getElementById("demo").innerHTML = xhttp.responseText;
})()
Where the file to read is ajax_info.txt, and the response function is the last three lines.

Related

How to get a certain line from xml from other webpage (url) in js?

const xhrRequest = new XMLHttpRequest();
xhrRequest.onload = function()
{
dump(xhrRequest.responseXML.documentElement.nodeName);
console.log(xhrRequest.responseXML.documentElement.nodeName);
}
xhrRequest.open("GET", "/website_url.xml")
xhrRequest.responseType = "document";
xhrRequest.send();
I'm trying to request a xml page from a page, but i'm unable to get certain line from xml in javascript. Thank you!
You can easily send requests to other pages with an AJAX http request found here: https://www.w3schools.com/js/js_ajax_intro.asp
Here is an example function:
function SendRequest(){
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
// Success
}
};
xmlhttp.open("GET", "example.com", true);
xmlhttp.send();
}
Now, about getting a value from the xml document, you can use .getElementsByTagName(). Notice that this is an array of elements so you have to append an index such as [0]
This would go inside the onreadystatechange of the http request
if(this.readyState == 4 && this.status == 200){
let xmlDocument = this.responseXML;
console.log(xmlDocument.getElementsByTagName("TestTag")[0].childNodes[0].nodeValue);
}
So if the xml document had an element like:
<TestTag>Hello</TestTag>
the function would print Hello

javascript - function with setInterval not starting immediately on page load

I have this code that continuously accesses a url at given intervals:
window.setInterval(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var valr5 = JSON.parse(this.responseText);
document.getElementById("wind").innerHTML = valr5.wind;
}
};
xmlhttp.open("GET", "sample.com/", true);
xmlhttp.send();
}, 30000);}
My problem is that the script would run after 30s, as set in the code. So the page is blank for 30s.
What I want to happen is on page load, the script will run so I won't see I blank page, and from that, access the URL every 30s or so.
How can I do this? thanks.
Save the function in a variable first, call the function, then call setInterval with it:
const updateWind = () => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var valr5 = JSON.parse(this.responseText);
document.getElementById("wind").innerHTML = valr5.wind;
}
};
xmlhttp.open("GET", "sample.com/", true);
xmlhttp.send();
};
updateWind();
window.setInterval(updateWind, 30000);

Read a file contents inside JavaScript, problem in accessing data

This code is used to read a .txt file in Javascript:
function readFile(fileName) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
console.log(his.responseText);
return this.responseText
}
};
xhttp.open("GET", fileName, true);
xhttp.send();}
This code print out the file contents into the console.
I want to use the file content for further processing. When I try to read the contents using these two lines inside JavaScript:
contents = readFile("data.txt");
console.log(contents);
the console displays: undefined.
How can I fix that?
You can't use the asynchronous result in a synchronous way, instead you can call another function when the promise resolves and do what want there.
function readFile(fileName) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
console.log(his.responseText);
doSomething(this.responseText); //call the function when the promise resolves and do what you want there
}
};
xhttp.open("GET", fileName, true);
xhttp.send();
}
function doSomething(text) {
//do what you want to do with the text here. 'text' here is the responseText
console.log(text);
}

Javascript not returning AJAX data (JSON, PHP, AJAX) [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I've got two functions in Javascript. One gets JSON data from a php file.
{"company_name":"","job_title":"Superhero","unix_time_convert":"Posted 06th of September '18","link":"2"}
The javascript function to return the JSON is this:
function assignJsonData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = (this.response);
return data;
//alert( data );
}
};
xmlhttp.open("GET", 'test_echo.php?row=1', true);
xmlhttp.send();
}
Notice that alert( data ); will return the JSON data in a box.
But when I assign the function to a variable elsewhere like so, it returns undefined.
window.onload = function () {
var data = assignJsonData();
alert(data);
}
What am I missing here?
Sorry to ask, I've been on this for hours...
Thanks
Andy
You should use callBack to retrieve data from ajax request , and get data when ajax request is finieshed , your could should look like :
function assignJsonData(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this.response);
}
};
xmlhttp.open("GET", 'test_echo.php?row=1', true);
xmlhttp.send();
}
window.onload = function () {
assignJsonData(function(data){
alert(data);
});
}
As Jafar pointed, you should use a callback!
If you want to check the order the things is executed, run the code bellow.
var returnData = "";
function assignJsonData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(this.readyState, this.status);
if (this.readyState == 4 && this.status == 200) {
returnData = this.response;
console.log('enter');
//console.log(this.response);
//return data;
//alert( data );
}
};
xmlhttp.open("GET", 'https://jsonplaceholder.typicode.com/todos/1', true);
xmlhttp.send();
}
assignJsonData();
console.log("returnData: " + returnData);
XMLHttpRequest is asynchronous. You need to either use a callback or a Promise.
function assignJsonData(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = this.response
callback(data)
}
};
xmlhttp.open("GET", 'test_echo.php?row=1', true);
xmlhttp.send();
}
window.onload = function () {
assignJsonData(function(data) {
alert(data)
});
}
You need to use Promise.
Check - How do I promisify native XHR?
You don't have the data in alert, because the response is not ready I guess.

How print content about Response Content Type Json?

hello sorry for the question but i don't know like to do what i want...
If i run this link https://api.onwater.io/api/v1/results/10,10 API say if this point (latitude 10°N; longitude 10°E) is in water or land.
the result in this case is:
{"lat":9.999237824938984,"lon":10.000257977613291,"water":false}
How i can to print value's water ??
Thanks a lot
Assuming you are looking for an AJAX Call you can do it with pure JS like this
function callAjax() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
if (xmlhttp.status == 200) {
var response = JSON.parse(xmlhttp.responseText);
document.getElementById("myDiv").innerHTML = response.water;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "https://api.onwater.io/api/v1/results/10,10", true);
xmlhttp.send();
}
callAjax();
<div id="myDiv"></div>
Using jquery would be like this
$.ajax({
url: "https://api.onwater.io/api/v1/results/10,10",
context: document.body,
success: function(data){
console.log(data.water);
}
});
Normally you could access it by its property name:
const response = {"lat":9.999237824938984,"lon":10.000257977613291,"water":false}
console.log(response.water);
Assume that you're retrieving the data through AJAX
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200){
// parse the response to object
var obj = JSON.parse(this.responseText);
// print it out (obj.water and obj['water'] produces the same result)
alert(obj.water);
console.log(obj['water']); // prints it in console
}
};
xhr.open("GET", "https://api.onwater.io/api/v1/results/10,10", true);
xhr.send();
You can learn more about AJAX here.

Categories