javascript - function with setInterval not starting immediately on page load - javascript

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);

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

Logout request from Javascript to Flask

I'm trying to logout user from my web application using Flask-Login.
Here's my Javascript function:
function logout() {
var req = new XMLHttpRequest();
req.open("POST", "http://myaddress/logout", true);
req.withCredentials = true;
req.send();
Here's my Python function:
#app.route('/logout')
#login_required
def logout_function():
logout_user() # Built-in Flask-Login function
return app.send_static_file('login.html')
When I send my request from Javascript I receive 200, but the page remains still, because redirect doesn't happen. I tried changing the last line of Python function to return redirect(url_for('login_function')), but it didn't help.
Could it be my Javascript function that causes the problem?
You need to redirect to the logout page using JavaScript:
function logout() {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
window.location.replace("http://myaddress/logout.html");
}
};
req.open("POST", "http://myaddress/logout", true);
req.withCredentials = true;
req.send();
}
You can hardcode the logout-URL like shown above. In this case you just need to return a 200 status code:
return ('', 200)
If you want to return the url, you can access it with req.responseText:
Flask:
return (url_for('login_function'), 200)
JavaScript:
if (this.readyState == 4 && this.status == 200) {
window.location.replace(req.responseText);
}

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.

Somehow this won't show me an alert or any errors

somehow this code just blanks and isn't really doing anything.
Doesn't even show any errors.
So can Someone help?
function connectStart(mycon){ //connection start for contacting
return function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonReturn = JSON.parse(this.responseText);
mycon; //calls the makeAnn() Function
}
};
// mypref() stands for the preference code location for the myphp.php
xmlhttp.open("GET", mypref()+"myphp.php?q="+myvar,true);
xmlhttp.send();
}
}
function makeAnn(){
return function(){
console.log(jsonReturn);
if ( jsonReturn !== "NO"){
alert("Announcement Was Posted");
} else {
alert("Error Encoding Data");
}
} //end of return function()
}
function mainFunction(){ //is called by an onclick event
var myvar = "I Shall Return!";
connectStart(makeAnn()); // i used invocation to combine them
}
Somehow it never shows any actual complaints or anything on the console log.
No alerts or whatever.
Doesn't write the data sent to the php or database.
No nothing really.
And I have tried the Php and html, their both fine.
It's just this part of my code that won't work.
You are not calling the function inside your onreadystatechange handler. See below.
function connectStart(mycon){ //connection start for contacting
return function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonReturn = JSON.parse(this.responseText);
// mycon; //wouldn't do anything
mycon(); // THIS should work better...
}
};
// mypref() stands for the preference code location for the myphp.php
xmlhttp.open("GET", mypref()+"myphp.php?q="+myvar,true);
xmlhttp.send();
}
}
EDIT:
The other problem which I now noticed is that you are referencing jsonReturn way, way out of its scope.
function connectStart(mycon){ //connection start for contacting
return function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonReturn = JSON.parse(this.responseText);
mycon(jsonReturn); // pass jsonReturn as a parameter
}
};
// mypref() stands for the preference code location for the myphp.php
xmlhttp.open("GET", mypref()+"myphp.php?q="+myvar,true);
xmlhttp.send();
}
}
function makeAnn(){
return function(jsonReturn){ // pass in as a parameter
console.log(jsonReturn);
if ( jsonReturn !== "NO"){
alert("Announcement Was Posted");
} else {
alert("Error Encoding Data");
}
} //end of return function()
}
function mainFunction(){ //is called by an onclick event
var myvar = "I Shall Return!";
connectStart(makeAnn()); // i used invocation to combine them
}

Doing multiple XMLHttpRequest from different url

I'm trying to use XMLHttpRequest to get data from two different localhost ports. It will run the request as soon as the page loaded. And I will run a function as soon as it finish getting the data from the 2 ports. But so far, only can get the data from local port 1000. I have check the ports already but no problem. The problem must have been the javascript.
js:
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:1000/data1";
var info1;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
info1 = jQuery.parseJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
var xmlhttp1 = new XMLHttpRequest();
var url1 = "http://localhost:2000/data2";
var info2;
xmlhttp1.onreadystatechange = function () {
if (xmlhttp1.readyState == 4 && xmlhttp1.status == 200) {
info2 = jQuery.parseJSON(xmlhttp1.responseText);
reload(info1, info2);
}
}
xmlhttp1.open("GET", url1, true);
xmlhttp1.send();
function reload(info1, info2) {
alert("success");
// processing the data
}
Is it that something wrong with the javascript?

Categories