I have this function. With xhr.response I get my json values. Question: how do I attach these JSON values to my HTML labels? Thank you.
Unrelevant question: Does anyone know of a good website where beginning JSON concepts are compactly summarized?
For example country to the label country.
function initPage(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://ip-api.com/json", false);
xhr.send();
console.log(xhr.status);
console.log(xhr.statusText);
console.log(xhr);
console.log(xhr.response);
}
JSON Output:
Visit http://ip-api.com/json
Desired HTML:
<label id="landcode"></label>
<label id="country"></label>
<label id="regio"></label>
<label id="city"></label>
<label id="postcode"></label>
<label id="latitude"></label>
<label id="longitude"></label>
<label id="ip"></label>
You are doing XMLHttpRequest() call, you need to check if the status == 200 (2xx Success / 200 OK) and readyState = 4 (DONE):
<button type="button" onclick="initPage()">Change Content</button>
<br>
<label id="country">Before XMLHttpRequest CALL</label>
<script>
function initPage() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("country").innerHTML =
this.responseText;
}
};
xhr.open("GET", "http://ip-api.com/json", false);
xhr.send();
console.log(xhr.status);
console.log(xhr.statusText);
console.log(xhr);
console.log(xhr.response);
}
</script>
Related
I formulated this XHR request by converting it from curl.
the curl request works but can't get this one working. plz help.
var url = "https://networkappers.com/api/port.php?ip=172.217.13.238&port=80";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Referer", "https://www.networkappers.com/tools/open-port-checker");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}
};
xhr.send();
I have a problem with uploading a file to a node server via HTML. In the page I have this input:
<input type="file" id = "csvFile" />
<input type="submit" name="submit" onclick="send_data()" />
Then I have the send_data function that looks like this:
function send_data(){
let file = document.getElementById("csvFile");
const xhr = new XMLHttpRequest();
xhr.open("GET", file, true);
xhr.setRequestHeader("Content-type", "text/csv");
xhr.onreadystatechange = () =>{
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200){
console.log("done");
}
xhr.send();
}
Here there is the first problem, because the arrow function of the ready state never executes.
In any case, it's the first time I do something like this, so I don't know how I can make sure that my server gets the file and processes it. Can someone help me?
This should do the trick:
let file = document.getElementById("csvFile").files[0];
let xhr = new XMLHttpRequest();
let formData = new FormData();
formData.append("csvFile", file);
xhr.open("POST", '${your_full_address}');
xhr.onreadystatechange = function () {
// In local files, status is 0 upon success in Mozilla Firefox
if (xhr.readyState === XMLHttpRequest.DONE) {
var status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
// The request has been completed successfully
console.log(xhr.responseText);
} else {
// Oh no! There has been an error with the request!
}
}
};
xhr.send(formData);
Refer: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange
I'm new in Javascript and i'm trying to make an http request to fetch some data and display the results in html. I'm fetching the results and update the html code, but then the html code inside body reloads and shows the default values. My code is,
<head>
<script>
function httpGetAsync() {
var results = new Array(3);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
xhr.onreadystatechange = processRequest;
function processRequest() {
if (xhr.readyState == 4 && xhr.status == 200) {
// populate here results array
// i change the value with the following line
document.getElementById("title_1").innerText = "fetched_value";
}
}
}
</script>
</head>
<body>
<div class="search_btn">
<form id="search_form" method="get" onSubmit="return httpGetAsync()">
<input type="text" class="search" placeholder="Search" id="search">
<input type="submit" value="search" class="search_button">
</form>
</div>
<div id="one">
<p id="title_1">default</p>
</div>
</body>
The 'title_1' changes its text to 'fetched_value' but it then reloads and becomes 'default' again. What am i doing wrong?
It's because your onSubmit does not receive false. Simply add return false to httpGetAsync end
function httpGetAsync() {
var results = new Array(3);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
xhr.addEventListener(
"readystatechange",
function processRequest() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("title_1").innerText = "fetched_value";
}
},
false);
xhr.onreadystatechange = processRequest;
return false;
}
You need to prevent the default action on submit, which is to use the "action" attribute on the form element to reload the page (if it's not present the current page is reloaded).
function httpGetAsync(event) {
event.preventDefault();
...
}
How do you insert the correct "xhr" value into the HTML5 button?
I am not sure how this whole XMLHttpRequest works. I believe it takes: xml data, text, numbers or null from the HTML5 button input and prints it out in text input in this case but can it store a value in it to call on it later. That is the question!
<script type="text/javascript">
function readBody(xhr) {
var data;
if (!xhr.responseType || xhr.responseType === "text"){
data = xhr.responseText;
} else if (xhr.responseType === "document") {
data = xhr.responseXML;
} else {
data = xhr.response;
}
window.document.myform.xhr1.value = data;
return data;
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200); {
window.document.myform.readBodyxhr.value = readBody(xhr);
}
else {
alert(xhr.status);
}
xhr.open('GET', 'http://www.google.com', true);
xhr.send(null);
}
</script>
...HTML5
<input type="button" name="XMLHttpRequest" value="XMLHttpRequest" onclick="readBody(xhr)" />
<input type="text" name="xhr1" value="" size="4"/></td>
<input type="text" name="readBodyxhr" value="" size="4"/></td>
Move call to .open() and .send() outside of onreadystatechange handler.
Substituted onload and onerror for onreadystatechange. ; following if condition is a syntax error. Note also, XMLHttpRequest with true passed at third parameter at .open() sets load handler to return results asynchronously.
<script type="text/javascript">
var url = "https://gist.githubusercontent.com/guest271314/6a76aa9d2921350c9d53/raw/1864137bfd2eb62705bd0e71175048a28b3253e6/abc.txt";
function readBody() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
window.document.myform
.readBodyxhr.value = xhr.responseText;
}
xhr.onerror = function() {
alert(xhr.status);
}
xhr.open("GET", url, true);
xhr.send(null);
}
</script>
...HTML5
<form name="myform">
<input type="button" name="XMLHttpRequest" value="XMLHttpRequest" onclick="readBody()" />
<input type="text" name="xhr1" value="" size="4" />
<input type="text" name="readBodyxhr" value="" size="4" />
</form>
I have created a simple ajax request:
var params = "postdata=" + mydata;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("data").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "data.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
And this is the HTML code:
<div id="data">
<img src="/images/preload.gif" />
<b style="color:#9ca6dc;font-size:12px;">Wait</b>
</div>
The problem is that the preload.gif and "Wait" text appears only sometimes and not always.
Why ? How can I resolve that ?
The only explanation is that AJAX request works too quickly to see the content (as Alessandro Pezzato said). If you don't see it the readyState of XMLHTTP request had to change.
Or you have some other Javascript which runs asynchronously and does changes on the same content.