ajax fail recursive pure javascript - javascript

var object = {
ver: "version",
time: "time",
xhr: new XMLHttpRequest(),
method: "POST",
error: JSON.stringify({
api: object.ver,
err: "server",
time: object.time
});
},
servers = {
srv1:"http://srv1.example.com",
srv2:"http://srv2.example.com",
srvErr:"http://err.example.com"
},
data = JSON.stringify({
api: object.ver,
time: object.time
});
function cors(object, server) { // Cross domain XHR request
if ("withCredentials" in object.xhr) {
object.xhr.open(object.method, server, true);
} else if (typeof XDomainRequest != "undefined") {
object.xhr = new XDomainRequest();
object.xhr.open(object.method, server);
} else {
object.xhr = null;
}
return object.xhr;
}
function ajax(data, object, server, servers) {;
try {
var x = cors(object, server);
x.setRequestHeader("Content-Type","application/json;charset=UTF-8", 'X-Requested-With', 'XMLHttpRequest');
x.onreadystatechange = function() {
if (x.readyState != 4) {
return;
}
if(x.status==200){
console.log("success: ", data);
}
n++;
if (x.status != 200) {
console.log("2", data);
ajax(data, object, servers.srv2, server);
//second call
ajax(object.error, object, servers.srvErr, servers);
//third call
}
};
x.send(data);
} catch (e) {
console.log(e.message);
}
}
ajax(data, object, servers.srv1, servers); // first call
I try to make two async ajax calls inside ajax call to my own servers, in case of outer ajax call did not succeed. I get result, that only last ajax call is really goes out of browser to the server. I can't use callback, as I only need this two ajax calls in case first one fail.
The main trick - I can't use jQuery, and this ajax should be cross-browser compatible -> IE8,9. I already test it on my servers, and it work with cross domain. the only thing is breaking my mind, how to make this code to run 2 ajax calls on fail of first one. I do not need COMET( subscribe) or WebSockets.
Please help me somebody.

Here's how to modify your program follow to behave as you expect it to:
...
if (x.status != 200) {
console.log("t2", d, "N: ", n);
// I SUPPOSE HERE'S THE RIGHT PLACE TO INCREMENT YOUR COUNTER
n++;
try {
f(d); // throw error with data json
} catch (e) {
a(e.message, p, r.t1, r, n);
}
try {
e(p, s, r); // throw error with error json
} catch (e) {
a(e.message, p, r.err, r, n);
}
}
....
You currently experience an unexpected behaviour because the n you see in the case of a request that returns with an error was updated in a wrong context.

Related

Ajax call issues more callbacks than expected

I have this code to make an ajax request, but according to Chrome Inspector the callback associated with the request is being called twice (by this I mean the response is being logged into the console twice), 2 more logs are being printed without any content. Here's the code:
var ajax = {
pull: function (settings) {
settings.type = 'get';
settings.callback = typeof (settings.callback) === 'function' ? settings.callback : false;
settings.data = settings.data ? settings.data : null;
return this.request(settings.url, settings.type, settings.callback, settings.data);
},
request: function (url, type, callback, data) {
var ids = ['MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP'],
xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
for (var i = 0; i < ids.length; i++) {
try {
xhr = new ActiveXObject(ids[i]);
break;
} catch (e) {}
}
}
if (callback) {
xhr.onreadystatechange = function () {
callback(xhr);
};
}
xhr.open(type, url, true);
if (type.toUpperCase() === 'GET') {
xhr.send();
} else if (type.toUpperCase() === 'POST') {
xhr.send(data);
}
}
}
ajax.pull({
url: 'http://localhost/my/twtools/scripts/ajax.php',
callback: function (xhr) {
console.log(xhr.response);
}
});
xhr.onreadystatechange has several steps (numbered from 0 top 4 I do believe something like 0 = uninitialized, 1 = starting etc, although I can't rember the exact names of the steps anymore, a quick google should find them), and each step is calling your callback. If I remember correctly, the last stage is 4, so I do believe you need to check something like this
if (xhr.readyState == 4 && xhr.status == 200)
{
// call has finished successfully
}
inside you callback, i.e. to check that it is all finished and got a successful response
I've been spoilt by jQuery these days (so much easier to do with jQuery), been quite a while since I wrote raw ajax
You're using onreadystatechange, which gets called more than once (once each state change).
Try using
xhr.onload = function() {
callback(xhr);
};

Form submit using Ajax

I need to submit the a form using Ajax with POST method.The code is as follows,
function persistPage(divID,url,method){
var scriptId = "inlineScript_" + divID;
var xmlRequest = getXMLHttpRequest();
xmlRequest.open("POST",url,true);
xmlRequest.onreadystatechange = function(){
alert(xmlRequest.readyState + " :" + xmlRequest.status);
if (xmlRequest.readyState ==4 || xmlRequest.status == 200)
document.getElementById(divID).innerHTML=xmlRequest.responseText;
};
xmlRequest.open("POST", url, false);
alert(xmlRequest.readyState);
xmlRequest.send(null);
}
but the form is not submitting(request is not executed or no data posted).How to submit the form using Ajax.
Thanks
There's a few reasons why your code doesn't work. Allow me to break it down and go over the issues one by one. I'll start of with the last (but biggest) problem:
xmlRequest.send(null);
My guess is, you've based your code on a GET example, where the send method is called with null, or even undefined as a parameter (xhr.send()). This is because the url contains the data in a GET request (.php?param1=val1&param2=val2...). When using post, you're going to have to pass the data to the send method.
But Let's not get ahead of ourselves:
function persistPage(divID,url,method)
{
var scriptId = "inlineScript_" + divID;
var xmlRequest = getXMLHttpRequest();//be advised, older IE's don't support this
xmlRequest.open("POST",url,true);
//Set additional headers:
xmlRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');//marks ajax request
xmlRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencode');//sending form
The first of the two headers is not always a necessity, but it's better to be safe than sorry, IMO. Now, onward:
xmlRequest.onreadystatechange = function()
{
alert(xmlRequest.readyState + " :" + xmlRequest.status);
if (xmlRequest.readyState ==4 || xmlRequest.status == 200)
document.getElementById(divID).innerHTML=xmlRequest.responseText;
};
This code has a number of issues. You're assigning a method to an object, so there's no need to refer to your object using xmlRequest, though technically valid here, this will break once you move the callback function outside the persistPage function. The xmlRequest variable is local to the function's scope, and cannot be accessed outside it. Besides, as I said before, it's a method: this points to the object directlyYour if statement is a bit weird, too: the readystate must be 4, and status == 200, not or. So:
xmlRequest.onreadystatechange = function()
{
alert(this.readyState + " :" + this.status);
if (this.readyState === 4 && this.status === 200)
{
document.getElementById(divID).innerHTML=this.responseText;
}
};
xmlRequest.open("POST", url, false);
alert(xmlRequest.readyState);//pointless --> ajax is async, so it will alert 0, I think
xmlRequest.send(data);//<-- data goes here
}
How you fill the data is up to you, but make sure the format matches the header: in this case 'content type','x-www-form-urlencode'. Here's a full example of just such a request, it's not exactly a world beater, since I was in the process of ditching jQ in favour of pure JS at the time, but it's serviceable and you might pick up a thing or two. Especially take a closer look at function ajax() definition. In it you'll see a X-browser way to create an xhr-object, and there's a function in there to stringify forms, too
POINTLESS UPDATE:
Just for completeness sake, I'll add a full example:
function getXhr()
{
try
{
return XMLHttpRequest();
}
catch (error)
{
try
{
return new ActiveXObject('Msxml2.XMLHTTP');
}
catch(error)
{
try
{
return new ActiveXObject('Microsoft.XMLHTTP');
}
catch(error)
{
//throw new Error('no Ajax support?');
alert('You have a hopelessly outdated browser');
location.href = 'http://www.mozilla.org/en-US/firefox/';
}
}
}
}
function formalizeObject(form)
{//we'll use this to create our send-data
recursion = recursion || false;
if (typeof form !== 'object')
{
throw new Error('no object provided');
}
var ret = '';
form = form.elements || form;//double check for elements node-list
for (var i=0;i<form.length;i++)
{
if (form[i].type === 'checkbox' || form[i].type === 'radio')
{
if (form[i].checked)
{
ret += (ret.length ? '&' : '') + form[i].name + '=' + form[i].value;
}
continue;
}
ret += (ret.length ? '&' : '') + form[i].name +'='+ form[i].value;
}
return encodeURI(ret);
}
function persistPage(divID,url,method)
{
var scriptId = "inlineScript_" + divID;
var xmlRequest = getXhr();
xmlRequest.open("POST",url,true);
xmlRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencode');
xmlRequest.onreadystatechange = function()
{
alert(this.readyState + " :" + this.status);
if (this.readyState === 4 && this.status === 200)
{
document.getElementById(divID).innerHTML=this.responseText;
}
};
xmlRequest.open("POST", url, false);
alert(xmlRequest.readyState);
xmlRequest.send(formalizeObject(document.getElementById('formId').elements));
}
Just for fun: this code, untested, but should work allright. Though, on each request the persistPage will create a new function object and assign it to the onreadystate event of xmlRequest. You could write this code so that you'll only need to create 1 function. I'm not going into my beloved closures right now (I think you have enough on your plate with this), but it's important to know that functions are objects, and have properties, just like everything else:Replace:
xmlRequest.onreadystatechange = function()
{
alert(this.readyState + " :" + this.status);
if (this.readyState === 4 && this.status === 200)
{
document.getElementById(divID).innerHTML=this.responseText;
}
};
With this:
//inside persistPage function:
xmlRequest.onreadystatechange = formSubmitSuccess;
formSubmitSuccess.divID = divID;//<== assign property to function
//global scope
function formSubmitSuccess()
{
if (this.readyState === 4 && this.status === 200)
{
console.log(this.responseText);
document.getElementById(formSubmitSuccess.divID).innerHTML = this.responseText;
//^^ uses property, set in persistPAge function
}
}
Don't use this though, as async calls could still be running while you're reassigning the property, causing mayhem. If the id is always going to be the same, you can, though (but closures would be even better, then).
Ok, I'll leave it at that
This code can let you understand. The function SendRequest send the request and build the xmlRequest through the GetXMLHttpRequest function
function SendRequest() {
var xmlRequest = GetXMLHttpRequest(),
if(xmlRequest) {
xmlRequest.open("POST", '/urlToPost', true)
xmlRequest.setRequestHeader("connection", "close");
xmlRequest.onreadystatechange = function() {
if (xmlRequest.status == 200) {
// Success
}
else {
// Some errors occured
}
};
xmlRequest.send(null);
}
}
function GetXMLHttpRequest() {
if (navigator.userAgent.indexOf("MSIE") != (-1)) {
var theClass = "Msxml2.XMLHTTP";
if (navigator.appVersion.indexOf("MSIE 5.5") != (-1)) {
theClass = "Microsoft.XMLHTTP";
}
try {
objectXMLHTTP = new ActivexObject(theClass);
return objectXMLHTTP;
}
catch (e) {
alert("Errore: the Activex will not be executed!");
}
}
else if (navigator.userAgent.indexOf("Mozilla") != (-1)) {
objectXMLHTTP = new XMLHttpRequest();
return objectXMLHTTP;
}
else {
alert("!Browser not supported!");
}
}
take a look at this page. In this line: req.send(postData); post data is an array with values that should be posted to server. You have null there. so nothing is posted. You just call request and send no data. In your case you must collect all values from your form, as XMLHTTPRequest is not something that can simply submit form. You must pass all values with JS:
var postData = {};
postData.value1 = document.getElementById("value1id").value;
...
xmlRequest.send(postData);
Where value1 will be available on server like $_POST['value'] (in PHP)
Also there might be a problem with URL or how you are calling persistPage. persistPage code looks ok to me, but maybe I'm missing something. Also you can take a look if you have no errors in console. Press F12 in any browser and find console tab. In FF you may need to install Firebug extention. Also there you will have Network tab with all requests. Open Firebug/Web Inspector(Chrome)/Developer Toolbar(IE) and check if new request is registered in its network tab after you call persistPage.
I found you've invoked the
xmlRequest.open()
method twice, one with async param as true and the other as false. What exactly do you intend to do?
xmlRequest.open("POST", url, true);
...
xmlRequest.open("POST", url, false);
If you want to send asynchronous request, pls pass the param as true.
And also, to use 'POST' method, you'd better send the request header as suggested by Elias,
xmlRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencode');
Otherwise, you may still get unexpected issues.
If you want a synchronous request, actually you may handle the response directly right after you send the request, just like:
xmlRequest.open("POST", url, false);
xmlRequest.send(postData);
// handle response here
document.getElementById(scriptId).innerHTML = xmlRequest.responseText;
Hope this helps.

Repeat failed XHR

Is there any common way, example or code template how to repeat a XHR that failed due to connection problems?
Preferably in jQuery but other ideas are welcome.
I need to send some application state data to a database server. This is initiated by the user clicking a button. If the XHR fails for some reason I need to make sure that the data is sent later (no interaction needed here) in the correct order (the user may press the button again).
Here's how I would do it:
function send(address, data) {
var retries = 5;
function makeReq() {
if(address == null)
throw "Error: File not defined."
var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
if(req == null)
throw "Error: XMLHttpRequest failed to initiate.";
req.onload = function() {
//Everything's peachy
console.log("Success!");
}
req.onerror = function() {
retries--;
if(retries > 0) {
console.log("Retrying...");
setTimeout(function(){makeReq()}, 1000);
} else {
//I tried and I tried, but it just wouldn't work!
console.log("No go Joe");
}
}
try {
req.open("POST", address, true);
req.send(data); //Send whatever here
} catch(e) {
throw "Error retrieving data file. Some browsers only accept cross-domain request with HTTP.";
}
}
makeReq();
}
send("somefile.php", "data");
To make sure everything is sent in the right order, you could tack on some ID variables to the send function. This would all happen server-side though.
And of course, there doesn't need to be a limit on retries.
jQuery provides an error callback in .ajax for this:
$.ajax({
url: 'your/url/here.php',
error: function(xhr, status, error) {
// The status returns a string, and error is the server error response.
// You want to check if there was a timeout:
if(status == 'timeout') {
$.ajax();
}
}
});
See the jQuery docs for more info.

How do I check if file exists in jQuery or pure JavaScript?

How do I check if a file on my server exists in jQuery or pure JavaScript?
With jQuery:
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
EDIT:
Here is the code for checking 404 status, without using jQuery
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
Small changes and it could check for status HTTP status code 200 (success), instead.
EDIT 2: Since sync XMLHttpRequest is deprecated, you can add a utility method like this to do it async:
function executeIfFileExist(src, callback) {
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (this.readyState === this.DONE) {
callback()
}
}
xhr.open('HEAD', src)
}
A similar and more up-to-date approach.
$.get(url)
.done(function() {
// exists code
}).fail(function() {
// not exists code
})
This works for me:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
i used this script to add alternative image
function imgError()
{
alert('The image could not be loaded.');
}
HTML:
<img src="image.gif" onerror="imgError()" />
http://wap.w3schools.com/jsref/event_onerror.asp
So long as you're testing files on the same domain this should work:
function fileExists(url) {
if(url){
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.send();
return req.status==200;
} else {
return false;
}
}
Please note, this example is using a GET request, which besides getting the headers (all you need to check weather the file exists) gets the whole file.
If the file is big enough this method can take a while to complete.
The better way to do this would be changing this line: req.open('GET', url, false); to req.open('HEAD', url, false);
Here's how to do it ES7 way, if you're using Babel transpiler or Typescript 2:
async function isUrlFound(url) {
try {
const response = await fetch(url, {
method: 'HEAD',
cache: 'no-cache'
});
return response.status === 200;
} catch(error) {
// console.log(error);
return false;
}
}
Then inside your other async scope, you can easily check whether url exist:
const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');
console.log(isValidUrl); // true || false
I was getting a cross domain permissions issue when trying to run the answer to this question so I went with:
function UrlExists(url) {
$('<img src="'+ url +'">').load(function() {
return true;
}).bind('error', function() {
return false;
});
}
It seems to work great, hope this helps someone!
All the other answers can fail due to cache!
Making a HTTP request to a file on server can be intercepted with HTTP cache and the cached response is then returned. But the file may be deleted on the server in the meantime, so ignoring cache may return false positive results.
Proper solution would be to create non-cached HTTP HEAD request. Nik Sumeiko's answer uses no-cache header which means that the response can be cached, but must be revalidated before reuse. In this case the server may return 304: Not Modified, which is not 200: OK and thus false negative.
To avoid cache, the correct header is Cache-Control: no-store
File can exist without HTTP 200 response
You should also keep in mind that redirection (301: Moved Permanently, 307: Temporary Redirect or 308: Permanent Redirect) may occur, so the file can exist elsewhere and may be returned from different location: depending on the use-case, one may choose to follow redirection instead of returning false in this case.
Also keep in mind that background requests will be blocked if you check file existence on different domain and its CORS policy is not opened to your server. In this case 403: Forbidden is usually returned, which doesn't mean file does not exist but file is unavailable. Last but not least, the same applies to 500: Internal Server Error response, which means that the HTTP server failed to handle the request, but the file can be available otherwise, like by FTP.
The following code will return true if the file exists, false if not or undefined if the file is unavailable or redirected:
const fileExists = file =>
fetch(file, {method: 'HEAD', cache: 'no-store'})
.then(response => ({200: true, 404: false})[response.status])
.catch(exception => undefined);
fileExists("yourFile.html").then(yes => yes && alert("yourFile.html exists"));
// or in the async scope...
let yourFileExists = await fileExists("yourFile.html");
if(yourFileExists) console.log("It is there!")
else if(yourFileExists===false) console.log("Nope, it was deleted.");
else console.log("You are not worthy the answer, puny human!");
Modern and obsolete approaches
Since we live in the future now, I would also recommend:
$.ajax() obsolete, don't use in new projects
XMLHttpRequest() obsolete, don't use in new projects
fetch() modern approach, use it if you are free to choose
Note GET/POST methods (like <img src...>) are not appropriate here as they waste network traffic by downloading the file (imagine the worst scenario with high resolution photo and user with paid mobile data in area with poor connectivity)
Note Modern PWA approach is to use Cache API with serviceWorker's fetch event which intercepts the communication between the client and HTTP cache. In the example in the link, there should be something like
if(event.request.cache=="no-store") {
// avoid cache storage and pass the request in the chain
// client - cache storage - HTTP cache - server
return fetch(event.request);
}
Without this, the cache settings may be ignored and there may be no way to detect the remote file existence from the main thread with the serviceWorker running - illustrated
here.
JavaScript function to check if a file exists:
function doesFileExist(urlToFile)
{
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
if (xhr.status == "404") {
console.log("File doesn't exist");
return false;
} else {
console.log("File exists");
return true;
}
}
I use this script to check if a file exists (also it handles the cross origin issue):
$.ajax(url, {
method: 'GET',
dataType: 'jsonp'
})
.done(function(response) {
// exists code
}).fail(function(response) {
// doesnt exist
})
Note that the following syntax error is thrown when the file being checked doesn't contain JSON.
Uncaught SyntaxError: Unexpected token <
For a client computer this can be achieved by:
try
{
var myObject, f;
myObject = new ActiveXObject("Scripting.FileSystemObject");
f = myObject.GetFile("C:\\img.txt");
f.Move("E:\\jarvis\\Images\\");
}
catch(err)
{
alert("file does not exist")
}
This is my program to transfer a file to a specific location and shows alert if it does not exist
An async call to see if a file exists is the better approach, because it doesn't degrade the user experience by waiting for a response from the server. If you make a call to .open with the third parameter set to false (as in many examples above, for example http.open('HEAD', url, false); ), this is a synchronous call, and you get a warning in the browser console.
A better approach is:
function fetchStatus( address ) {
var client = new XMLHttpRequest();
client.onload = function() {
// in case of network errors this might not give reliable results
returnStatus( this.status );
}
client.open( "HEAD", address, true );
client.send();
}
function returnStatus( status ) {
if ( status === 200 ) {
console.log( 'file exists!' );
}
else {
console.log( 'file does not exist! status: ' + status );
}
}
source: https://xhr.spec.whatwg.org/
This is an adaptation to the accepted answer, but I couldn't get what I needed from the answer, and had to test this worked as it was a hunch, so i'm putting my solution up here.
We needed to verify a local file existed, and only allow the file (a PDF) to open if it existed. If you omit the URL of the website, the browser will automatically determine the host name - making it work in localhost and on the server:
$.ajax({
url: 'YourFolderOnWebsite/' + SomeDynamicVariable + '.pdf',
type: 'HEAD',
error: function () {
//file not exists
alert('PDF does not exist');
},
success: function () {
//file exists
window.open('YourFolderOnWebsite/' + SomeDynamicVariable + '.pdf', "_blank", "fullscreen=yes");
}
});
First creates the function
$.UrlExists = function(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
After using the function as follows
if($.UrlExists("urlimg")){
foto = "img1.jpg";
}else{
foto = "img2.jpg";
}
$('<img>').attr('src',foto);
Here's my working Async Pure Javascript from 2020
function testFileExists(src, successFunc, failFunc) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState === this.DONE) {
if (xhr.status === 200) {
successFunc(xhr);
} else {
failFunc(xhr);
}
}
}
// xhr.error = function() {
// failFunc(xhr);
// }
// xhr.onabort = function() {
// failFunc(xhr);
// }
// xhr.timeout = function() {
// failFunc(xhr);
// }
xhr.timeout = 5000; // TIMEOUT SET TO PREFERENCE (5 SEC)
xhr.open('HEAD', src, true);
xhr.send(null); // VERY IMPORTANT
}
function fileExists(xhr) {
alert("File exists !! Yay !!");
}
function fileNotFound(xhr) {
alert("Cannot find the file, bummer");
}
testFileExists("test.html", fileExists, fileNotFound);
I could not force it to come back with any of the abort, error, or timeout callbacks.
Each one of these returned a main status code of 0, in the test above, so
I removed them. You can experiment.
I set the timeout to 5 seconds as the default seems to be very excessive.
With the Async call, it doesn't seem to do anything without the send() command.
What you'd have to do is send a request to the server for it to do the check, and then send back the result to you.
What type of server are you trying to communicate with? You may need to write a small service to respond to the request.
This doesn't address the OP's question, but for anyone who is returning results from a database: here's a simple method I used.
If the user didn't upload an avatar the avatar field would be NULL, so I'd insert a default avatar image from the img directory.
function getAvatar(avatar) {
if(avatar == null) {
return '/img/avatar.jpg';
} else {
return '/avi/' + avatar;
}
}
then
<img src="' + getAvatar(data.user.avatar) + '" alt="">
It works for me, use iframe to ignore browsers show GET error message
var imgFrame = $('<iframe><img src="' + path + '" /></iframe>');
if ($(imgFrame).find('img').attr('width') > 0) {
// do something
} else {
// do something
}
I wanted a function that would return a boolean, I encountered problems related to closure and asynchronicity. I solved this way:
checkFileExistence= function (file){
result=false;
jQuery.ajaxSetup({async:false});
$.get(file)
.done(function() {
result=true;
})
.fail(function() {
result=false;
})
jQuery.ajaxSetup({async:true});
return(result);
},

How do I make Ajax calls at intervals without overlap?

I'm looking to setup a web page that samples data via AJAX calls from an embedded web-server. How would I set up the code so that one request doesn't overlap another?
I should mention I have very little JavaScript experience and also a compelling reason not to use external libraries of any size bigger than maybe 10 or so kilobytes.
You may want to consider the option of relaunching your AJAX request ONLY after a successful response from the previous AJAX call.
function autoUpdate()
{
var ajaxConnection = new Ext.data.Connection();
ajaxConnection.request(
{
method: 'GET',
url: '/web-service/',
success: function(response)
{
// Add your logic here for a successful AJAX response.
// ...
// ...
// Relaunch the autoUpdate() function in 5 seconds.
setTimeout(autoUpdate, 5000);
}
}
}
This example uses ExtJS, but you could very easily use just XMLHttpRequest.
NOTE: If you must have an exact interval of x seconds, you would have to keep track of the time passed from when the AJAX request was launched up to the setTimeout() call, and then subtract this timespan from the delay. Otherwise, the interval time in the above example will vary with the network latency and with the time to processes the web service logic.
I suggest you use a small toolkit like jx.js (source). You can find it here: http://www.openjs.com/scripts/jx/ (less than 1k minified)
To setup a request:
jx.load('somepage.php', function(data){
alert(data); // Do what you want with the 'data' variable.
});
To set it up on an interval you can use setInterval and a variable to store whether or not a request is currently occuring - if it is, we simple do nothing:
var activeRequest = false;
setInterval(function(){
if (!activeRequest) {
// Only runs if no request is currently occuring:
jx.load('somepage.php', function(data){
activeRequest = false;
alert(data); // Do what you want with the 'data' variable.
});
}
activeRequest = true;
}, 5000); // Every five seconds
AJAX, despite the name, need not be asynchronous.
Here is the asynchronous method...
var req;
function ajax(method,url,payload,action)
{
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
req.onreadystatechange = action;
req.open(method, url, true);
req.send(payload);
}
else if (window.ActiveXObject)
{
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = action;
req.open(method, url, true);
req.send(payload);
}
else
{
alert("Could not create ActiveXObject(Microsoft.XMLHTTP)");
}
}
}
...but here is a synchronous equivalent...
function sjax(method,url,payload,action)
{
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
req.open(method, url, false);
req.send(payload);
action();
}
else if (window.ActiveXObject)
{
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = action;
req.open(method, url, false);
req.send(payload);
}
else
{
alert("Could not create ActiveXObject(Microsoft.XMLHTTP)");
}
}
}
... and here is a typical action ...
function insertHtml(target)
{
var pageTarget = arguments[0];
if (req.readyState == 4) // 4 == "loaded"
{
if (req.status == 200) // 200 == "Ok"
{
if (req.responseText.indexOf("error") >= 0)
{
alert("Please report the following error...");
pretty = req.responseText.substring(req.responseText.indexOf("error"),1200);
pretty = pretty.substring(0,pretty.indexOf("\""));
alert(pretty + "\n\n" + req.responseText.substring(0,1200));
}
else
{
div = document.getElementById(pageTarget);
div.innerHTML = req.responseText;
dimOff();
}
}
else
{
alert("Could not retreive URL:\n" + req.statusText);
}
}
}

Categories

Resources