Open link in browser with different params every 5 second - javascript

I want to open link example.com/id= with a different ids every 5 second using JS/jQuery.
I tried this:
<script type='text/javascript'>
setInterval(function() {
var i = 1;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
var add = 'example.com?id='+i;
request.open('GET', add, true);
i = i + 1;
request.send();
}, 5000);
</script>
but this is not working for me.
What should I do?

Since you've tagged it with jquery, here is one way:
$(function() {
var id = 1;
setInterval(function(){
$.get("example.com", { id: id }, function(data) {
console.log(data);
id++;
})
.fail(function(xhr, status, error) {
console.log("XHR:: " + xhr + " | Status:: " + status + " | Error:: " + error);
});
}, 5000);
});

You're using local variable i, so for every interval, this variable is reset to its initial value 1. Try using global variable instead of local:
var i = 1;
setInterval(function() {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
var add = 'example.com/id='+i;
request.open('GET', add, true);
i = i + 1;
request.send();
}, 5000);
or to avoid putting variable into global scope. You could wrap your function inside an immediate function. Like this:
(function(){
var i = 1;
setInterval(function() {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
var add = 'example.com/id='+i;
request.open('GET', add, true);
i = i + 1;
request.send();
}, 5000);
})();

DEMO
You have to specify the declaration of i var i=1;outside the setInterval()
Try this
code
var i = 1;
self.setInterval(function(){
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
alert(request.responseText); // alert response
}
}
var add = 'example.com?id='+i;
request.open('GET', add, true);
i = i + 1;
request.send();
},5000);
Hope this helps,thank you

Related

Ajax doesn't fire onreadystatechange

I know the URL is working as intended as i logged that to the console and it is fine. However I can't get "Good News" to log to the console when readyState == 4 and status == 200. I tried removing readState and it still wouldn't log. I tried logging the status and It would only fire once with a value of 0. This is the first time I am working with Ajax so any help is appreciated.
function setupRequest(){
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData () {
console.log('ran')
var url = 'localhost/bev/drinks.php';
var data = document.getElementById('input').value;
url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
request.send;
console.log('sent')
}
You need to actually call send(). You aren't doing anything whenever you say request.send;
function setupRequest() {
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData() {
console.log('ran')
var url = 'https://jsonplaceholder.typicode.com/posts';
var data = document.getElementById('input').value;
//url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
// You wrote (without parentheses):
///////////////////
// request.send; //
///////////////////
// You need to write
request.send();
console.log('sent')
}
<button type="button" id="send">Btn</button>
<input type="text" id="input">

How do I make an HTTP request to bitstamp?

I'm trying to use an API from bitstamp to fetch a currency trading price on my webpage.
I have researched this problem, but I still cannot get it to work as it always returns ERROR
The link used is https://www.bitstamp.net/api/ticker/ and the response should be last
Here is my code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.bitstamp.net/api/ticker/", true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response.last);
}
else {
window.alert("ERROR");
} }
Try this:
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonRes= JSON.parse(this.responseText);
if (jsonRes.hasOwnProperty('last')) {
document.getElementById("demo").innerHTML =
jsonRes.last;
alert(jsonRes.last);
}
}
};
xhttp.open("GET", "https://www.bitstamp.net/api/ticker", true);
xhttp.send();
}
<h2>Using the XMLHttpRequest object</h2>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
<p>last attribute is: <span id="demo"></span></p>
Here is one way:
<script src="./jquery.min.js">
//none secure web page ?
jQuery.get("https://www.bitstamp.net/api/ticker/", function (data, status)
{
// use response here; jQuery passes it as the first parameter
var response = JSON.parse(data);
window.alert(response.last);
console.log("MyFunc: " + "response : " + response + "\nStatus: " + status);
});
</script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.bitstamp.net/api/ticker/", true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response.last);
} else {
window.alert("ERROR");
}
}
}

Update DOM object in time intervals using JavaScript Worker

I'm trying to do some DOM objects updates in background.
What I mean is update tab title, and some elements regardless if user has tab active or not ( to show that there are new notifications )
I already found out, that Worker has to be used as it runs in background ( but don't have access to DOM). Tried as follows:
Main HTML:
...some html
<script>
$(document).ready(function ($) {
if (window.Worker) {
console.log('[DEBUG] Worker is supported')
var eventsWorker = new Worker("<c:url value="/resources/js/eventTimer.js" />");
setInterval(eventsWorker.postMessage([appUrl]), 20 * 1000);
//setEventsNonWorker()
eventsWorker.onmessage = function (e) {
console.log('Message received from worker' + e.data);
setEventsCount(e.data, appName, eventsTxt);
}
} else {
console.log('[DEBUG] Worker is NOT supported')
setEventsNonWorker()
}
});
function setEventsNonWorker(){
//regular update with setTimout and stuff
}
worker javascript file
function setEventsCount(count, appName, eventsTxt) {
var bell, text, countPar;
if (count > 0) {
bell = '<i class="fa fa-bell"></i> ';
countPar = '(' + count + ') ';
text = bell + eventsTxt + countPar;
$(".event-menu-li").html(text);
$("#event-menu-icon").html(bell + count)
document.title = countPar + appName;
} else {
bell = '<i class="fa fa-bell-o"></i> ';
text = bell + eventsTxt;
$(".event-menu-li").html(text);
$("#event-menu-icon").html(bell)
document.title = appName;
}
}
onmessage = function (e) {
var appUrl = e.data[0];
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
postMessage(xmlhttp.responseText);
}
};
xmlhttp.open("GET", appUrl, true);
xmlhttp.send();
}
The first call is working ( the event count is properly set ) but there are no more calls in 20 sec
Ok it turns out I was putting timeout in wrong place
html should be
//...
eventsWorker.postMessage([appUrl]);
eventsWorker.onmessage = function (e) {
console.log('Message received from worker' + e.data);
setEventsCount(e.data, appName, eventsTxt);
//...
which will just init worker , while worker.js should have the timeout
//...
onmessage = function (e) {
var appUrl = e.data[0];
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
postMessage(xmlhttp.responseText);
}
};
xmlhttp.open("GET", appUrl, true);
xmlhttp.send();
setInterval(function () {
xmlhttp.open("GET", appUrl, true);
xmlhttp.send();
}, 20*1000);
}

GET data from arduino

Hi guys this script gets the data from my arduino.
<script>
var nivel = 0;
var data_val = 0;
function GetArduinoInputs()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null) {
document.getElementById("input3").innerHTML = this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
data_val = this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
}
}
}
}
request.open("GET", "ajax_inputs" + nocache, true);
request.send(null);
setTimeout('GetArduinoInputs()', 200);
}
</script>
But I am not able to read the value of data_val on my other script:
<script>
var level = data_val;
</script>
Can someone help my out, please
You could use the same approach that you are using to store the value that you get from the server in the local HTML to retrieve the value in the "other script".
//from the "other script"
var level = document.getElementById("input3").innerHTML;

update ajax send() content

I'm trying to receive data from ajax call and then send this data back using ajax.
javascript code:setInterval (function ()
{
var xmlhttp = new XMLHttpRequest();
var content = "data=1";
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
content = "data=" + xmlhttp.responseText;
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST" , "execute-page.php" , true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(content);
},5000);
the problem now is that it keeps sending the old content. how can I update content variable with ajax response text?
Move the line var content = "data=1"; out of the function:
var content = "data=1";
setInterval (function ()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
content = "data=" + xmlhttp.responseText;
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST" , "execute-page.php" , true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(content);
},5000);

Categories

Resources