Cache pages using XMLHttpRequest - javascript

Everything is and is run on the same domain in the latest versions of the major browsers.
var xmlhttp = new XMLHttpRequest();
var sites = ["/page1", "/page2", "/page3"];
var cache = {};
function xhrStart(url) {
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function isOkXhr() {
return (xmlhttp.readyState == 4 &&
(xmlhttp.status >= 200 && xmlhttp.status < 300));
}
function reload() {
var len = sites.length;
var i;
for (i = 0; i < len; i++) {
var url = sites[i];
xmlhttp.onreadystatechange = function() {
if (isOkXhr())
cache[url] = xmlhttp.responseText;
}
xhrStart(url);
}
}
Reload function should be to cache all pages, but in fact all queries return Aborted in the debugger, except the last one. What could be the problem?

You are using one XHR object and keep writing over it in the loop. When you call open() it aborts the previous request. The for loop does not wait for the request.
Either create a new XHR request or wait til the other request is done before you make the next request.
var sites = ["/page1", "/page2", "/page3"];
var cache = {};
function xhrStart(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status >= 200 && xmlhttp.status < 300) {
cache[url] = xmlhttp.responseText;
} else {
//what are you going to do for error?
}
}
};
xmlhttp.send();
}
for (var i = 0; i < sites.length; i++) {
var url = sites[i];
xhrStart(url);
}

Related

XMLHttpRequest looping

I know this question has been asked before, but I tried to apply the answers with no results.
I'm trying to do multiple requests on the same domain with a for loop but it's working for the entire record of my array.
Here is the code I use:
function showDesc(str) {
var prod = document.getElementsByName("prod_item[]");
var xhr = [], i;
for (i = 0; i < prod.length; i++) {
var txtHint = 'txtHint10' + i;
(function(i) {
var xhr = new XMLHttpRequest();
var url = "getDesc.php?q=" + str;
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById(txtHint).innerHTML = xhr.responseText;
}
};
xhr.open("GET", url, false);
xhr.send();
})(i);
}
}
PHP
<select name="prod_item[]" id="prod_item.1" onchange="showDesc(this.options[this.selectedIndex].value)"></select>
<div id="txtHint100"></div>
and then I will use dynamic table for the prod_item field and div_id.
Is there any mistake in my code?

how to extract XML data from a URL link with jquery or javascript

I'm trying to rebuild some stuff I used in python but I'm finding it very tricky to pull data from an API link.
below is the function I'm trying to use to call the API and then get the data I want out of the XML file that the link 'https://api.bmreports.com/BMRS/FUELINSTHHCUR/v1?APIKey=&ServiceType=XML' returns however at the moment I'm struggling to get anything back at all
function GetXML(){
var request = new XMLHttpRequest();
request.open("GET", 'https://api.bmreports.com/BMRS/FUELINSTHHCUR/v1?APIKey=&ServiceType=XML', false);
request.send();
var xml = request.responseXML;
var fuel = xml.getElementsByTagName("fuelType");
for(var i = 0; i < users.length; i++) {
var fuel = fuel[i];
var fuelnames = user.getElementsByTagName("fuelType");
for(var j = 0; j < fuelnames.length; j++) {
alert(fuelnames[j].childNodes[0].nodeValue);
}
}
}
try this example:
var request = new XMLHttpRequest();
request.open("GET", 'https://api.bmreports.com/BMRS/FUELINSTHHCUR/v1?APIKey=&ServiceType=XML', true);
request.responseType = 'document';
request.overrideMimeType('text/xml');
request.onload = function () {
if (request.readyState === request.DONE) {
if (request.status === 200) {
console.log(request.responseXML);
}
}
};
request.send(null);

How to chain ajax calls using plain javascript

I've looked for the answers but couldn't find anything with plain Javascript. What would be the appropriate way? I tried to use the same approach repetitively but it didn't work. How can I solve this with pure Javascript?
function someFunction(){
var url = "someUrl";
var xmlhttp = new XMLHttpRequest ();
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function (){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
obj = JSON.parse(xmlhttp.responseText);
length = obj.ajax.length;
for(var i = 0; i < length; i++ ){
try{
var someVar = obj.ajax.elements[i].id;
var url2 = "someOtherUrl"+someVar+"/features";
var xmlhttp = new XMLHttpRequest ();
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function (){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
obj2 = JSON.parse(xmlhttp.responseText);
length2 = obj2.ajax.length;
for(var j= 0; j < length2; j++){
var elementNames = obj2.elements[j].name;
}
}
}
}
}
}
You can call that someFunction() recursively. To do so, You just have to invoke that same function after 200 ok response.
In following code I've added a restriction to return form recursive callback stack after a fixed amount of requests in chain.
EDIT : for multiple urls
callDone = 0;
urls = ['http://url1','http://url2','http://url3'];
totalCall = urls.length - 1;
function someFunction(){
//Edit: > Fetch url from array
var url = urls[ callDone ] ;
var xmlhttp = new XMLHttpRequest ();
xmlhttp .open( "GET", url, true);
xmlhttp .send();
xmlhttp .onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
//your stuff with response...
if( callDone < totalCall ){
callDone++;
someFunction();
}
else{
return;
}
}
}
}

AJAX not refreshing chat message section

I recently got a website aired and am having trouble getting the chat to work without having to have the user refresh the page (hence, the ajax). But the person on the other end still has to refresh in order to see the latest message. We're in the same room, so I can see if the chat refreshes or not; it doesn't, and here's the code
<script type="text/javascript">
var scroller = function(){
posts = document.getElementById("posts");
posts.scrollTop = posts.scrollHeight;
}
var menu = 3;
var checksum = function(){
if (menu == 3){
document.getElementById('smileys').style.display="block";
document.bob.smileyhider.innerHTML="−";
menu=1;
}
else {
document.getElementById('smileys').style.display="none";
document.bob.smileyhider.innerHTML="+";
menu=3;
}
}
//Chat ajax loader
var updater = 10;
function update(){
var xhr;
if(updater < 200){ updater = 200 }
if (window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }
else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status == 200){
document.getElementById('posts').innerHTML = xhr.responseText;
}
}
setTimeout(update, (++updater)*10);
xhr.open("GET","chatlog<?php echo date("d");?>.log",true);
xhr.send(null);
}
</script>
You are never actually calling update to kick off the ajax requests. I wouldn't nest it either
You want to use setInterval instead. setTimeout will only run once.
I would just use a static value for updater, like 3 seconds
/
var updater = 3000;
function update(){
var xhr;
if(updater < 200){ updater = 200 }
if (window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }
else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status == 200){
document.getElementById('posts').innerHTML = xhr.responseText;
}
}
xhr.open("GET","chatlog<?php echo date("d");?>.log",true);
xhr.send(null);
}
setInterval(update, updater);

Ajax - For loop

Ajax calls an array of four strings, I then want to print each string to a new line.
I have this code:
window.onload = function () {
var obj;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj = JSON.parse(xmlhttp.responseText);
for (var i = 0; i <= obj.length; i++) {
document.createTextNode(obj[i]);
}
}
}
xmlhttp.open("GET", "verify.php", true);
xmlhttp.send();
}
However, it doesn't work. obj.length returns 4, I don't know whether the loop isn't executing, or if I can't access the DOM? I'm very new to Javascript and DOM scripting.
Thanks in advance.
You need to actually put the nodes into the document.
var node;
for (var i = 0, n = obj.length; i < n; i++) { // NB: not <=
node = document.createTextNode(obj[i]);
document.body.appendChild(node);
node = document.createElement('br');
document.body.appendChild(node);
}
This only creates the textNode, you must still apply it to the DOM somehwere via appendChild:
https://developer.mozilla.org/en/DOM/document.createTextNode

Categories