Javascript make HTTP request on regular interval not working - javascript

I have a page to show the chat messages. I need to refresh the chat body every 30 seconds to load the new messages. I have set the interval to 30 seconds , the function is running , but its not making the HTTP request. Here is my code
function loadmessages(){
var ids = document.getElementById("pid").value;
var request = new XMLHttpRequest();
request.open("get", '/refresh_message/'+ ids );
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content);
request.onload = function(){
if(this.status == 200){
var resp = JSON.parse(this.responseText);
console.log(resp.message);
}
else{
console.log(this.status);
}
request.send(null);
}
}
loadmessages();
setInterval(function(){
loadmessages()
}, 30000);

Consistent indentation matters. You're putting request.send(null); inside the request.onload function, so of course it never gets sent in the first place. Try putting it outside, instead:
function loadmessages() {
var ids = document.getElementById("pid").value;
var request = new XMLHttpRequest();
request.open("get", '/refresh_message/' + ids);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content);
request.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.responseText);
console.log(resp.message);
} else {
console.log(this.status);
}
}
request.send(null);
}

Related

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

Can't get a global variable on http request function

it should be an easy one but I am stuck.
I would like to return the result of a function as a global variable. Here I have my function clearbit() for which I created the global variable clearbit_role.
But I can't alert this variable outside of the function... Any clue anyone?
Thanks!
EDIT: Added a fiddle here:
http://jsfiddle.net/luron01/sJ8Eu/9/
var clearbit_role ;
function clearbit (web){
var url = "https://prospector.clearbit.com/v1/people/search?domain=clearbit.com&seniorities[]=executive&seniorities[]=manager&limit=1";
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status == 200) {
var response = JSON.parse(request.responseText.replace('[','').replace(']',''));
var clearbit_fullname = response.name.fullName;
clearbit_role = response.role;
clearbit_role='test'
}
}
request.open('GET', url, true);
request.setRequestHeader("authorization", "Bearer sk_605e7e64cbb1ebcca9e28b8a97d23f22")
request.send();
}
clearbit()
alert(clearbit_role)
Thanks!
why don't you create the variable clearbit_role outside of the function
var clearbit_role ;
function clearbit (web){
var url = "myurl";
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status == 200) {
var response = JSON.parse(request.responseText.replace('[','').replace(']',''));
var clearbit_fullname = response.name.fullName;
clearbit_role = response.role;
}
}
request.open('GET', url, true);
request.setRequestHeader("authorization", "Bearer sk_1be5451252ba4e31518e9b")
request.send();
}
clearbit()
alert(clearbit_role)
The problem
is NOT in scoping, the clearbit_role variable is already a global variable. But the problem is clearbit function is take a time to make the http request.
so the alert function run before the clearbit_role variable declaration.
Solution
use a function to run after AJAX request done.
function clearbit (web){
var url = "myurl";
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status == 200) {
var response = JSON.parse(request.responseText.replace('[','').replace(']',''));
var clearbit_fullname = response.name.fullName;
clearbit_role = response.role;
someFunctionThatRunAfterAjaxDone(clearbit_role);
}
}
request.open('GET', url, true);
request.setRequestHeader("authorization", "Bearer sk_1be5451252ba4e31518e9b")
request.send();
}
clearbit()
// But all code you want to fun after AJAX done inside this function
function someFunctionThatRunAfterAjaxDone(clearbit_role) {
alert(clearbit_role)
}

clearInterval not working with XMLHttpRequest

I'm trying to get the result, next time of the game in database. I used XMLHttpRequest with 5s delay of setInterval to fetch data. If the status of the request is 200. The code works well. However, if the status is not 200. The clearInterval will not work but console.log still works.
var _resInterval;
_resInterval = setInterval(function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/index.php/forms/getDDResult/" + id, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status === 200) {
var _resp = JSON.parse(xhr.responseText);
console.log(_resp);
if (parseInt(_resp.interval) >= 0) {
clearInterval(_resInterval);
restartGame(parseInt(_resp.interval));
}
} else {
console.log("error");
clearInterval(_resInterval);
}
};
xhr.send();
}, 5000);
UPDATE: recursive function
function getGameResult() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/index.php/forms/getDDResult/" + id, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status === 200) {
var _resp = JSON.parse(xhr.responseText);
console.log(_resp);
if (parseInt(_resp.interval) >= 0 && _resp.result != "Not available") {
restartGame(parseInt(_resp.interval));
} else {
setTimeout(function() {
getGameResult();
}, 5000);
}
}
};
xhr.send();
}
Am I doing it the right way or should I change it to recursive function? Thanks.
-- Lara
The problem is that there's a possibility where the clearInterval is called and an XHR is pending a response. When the browser receives the response, the timer is long gone, but still has to handle the response.
If you want your periodic XHR to wait for the response of the previous before launching another, the recursive setTimeout is a better option.

How to get a data from html element from ajax responseText without jquery

I'd like to get data from ajax response, but this code not working:
var request = new XMLHttpRequest();
request.open("GET", "http://localhost/test/test.php", true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4) {
alert(request.responseText.document.getElementById('div1').innerHTML);
}
}
The console shows this error:
Uncaught TypeError: Cannot read property 'getElementById' of undefined.
Any ideas what's causing this?
You can use DOMParser to convert html string to document fragment
var request = new XMLHttpRequest();
request.open("GET", "http://localhost/test/test.php", true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var parser = new DOMParser();
var doc = parser.parseFromString(request.responseText, "text/html");
var elem = doc.getElementById("div1");
alert(elem.innerHTML);
}
}
alternatively, you can set the responseType to document
var request = new XMLHttpRequest();
request.open("GET", "file.html", true);
request.responseType = "document";
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var doc = request.response;
var elem = doc.getElementById("div1");
alert(elem.innerHTML);
}
}
plnkr http://plnkr.co/edit/lkpveDD31fYY1gmflK9W?p=preview
Request object isn't a DOM element nor does it have the methods that the native DOM has.
Fix your code with:
var request = new XMLHttpRequest();
request.open("GET", "http://localhost/test/test.php", true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4) {
alert(request.responseText);
}
}

onreadystatechange only firing once

I have the following code for my request:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) // state of 4 is 'done'. The request has completed
{
callback(req.responseText); // The .responseText property of the request object
} else { // contains the Text returned from the request.
console.log(req.readyState);
}
};
req.open("GET", url, true);
req.send();
However, the readyState is changing to 1 and firing correctly (I'm seeing it echoed in the console) but it simply won't progress to 2. After awhile it times out and I get this in the console:
Failed to load resource: net::ERR_CONNECTION_TIMED_OUT
Uncaught SyntaxError: Unexpected end of input
Anyone have any idea why this might be?
Put this
req.open("GET", url, true);
req.send();
above this line
req.onreadystatechange = function() {
Sorry all, this ended up being a VPN issue, not a scripting one.
function getLatestfileinAllPath(urls)?
{
for(i = 0;i<urls.length;i++){
run(i)
}
function run(){
var request = new XMLHttpRequest();
request.open('POST', url[i]);
request.send(JSON.stringify({"data":"some data"}));
request.onreadystatechange = function()
{
if (request.readyState === XMLHttpRequest.DONE && request.status == 200)
{
console.log(JSON.parse(request.response));
}
}
};
}
}

Categories