Explanation of downloadUrl() in Javascript? - javascript

I have looked far and wide for an explanation so that i am able to understand the above function. The situation which i have encountered it is in Google Maps API documentation:
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
If someone could shed some light it would be appreciated.

function downloadUrl(url, callback) { // pass a URL and a function to call on success
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest; // create an xmlhttprequest, native if possible, activeX for older IE - the construct is a ternary conditional statement
// set up handling of the state change, we only want the 4th
request.onreadystatechange = function() { // when the request changes state
// i.e from sending to having received
if (request.readyState == 4) { // request done
request.onreadystatechange = doNothing; // removed this anonymous function on 4th state (done)
callback(request.responseText, request.status); // call the supplied function with result
}
};
request.open('GET', url, true); // now initialize
request.send(null); // now execute
}
Update: it is these days (July 2018) more likely to find the XMLHttpRequest than the activeX, so any of the following are recommended:
switch the test around,
remove the test for activeX,
add a try/catch or
use Fetch

this code uses AJAX functionality in the browser to fetch the contents of the URL.

Related

Close specific XMLHttpRequest

How to "rebuild" function to close specific XMLHttpRequest? I have defined variable outside function to call xhr.abort(); everywhere I need. Now is possible, with this solution, close last running XMLHttpRequest if running more than one at same time - processes before last running are without control after replace xhr by re-calling _ajax()
var xhr;
function _ajax(data, callback) {
xhr = new XMLHttpRequest();
xhr.open('POST', window.location.pathname, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this);
}
};
xhr.send(data);
}
/* close fnc */
xhr.abort();
You could use xhr as an array and store there all the requests; then you can call abort on any one of them. Like:
var xhr=[];
function _ajax(data, callback) {
xhr.push(new XMLHpptRequest);
//etc
}
xhr[0].abort();
xhr.shift(); //get rid of the aborted request

Javascript - Ajax onload Callback Fail

I want to make an ajax function using plain javascript. I am able to do it using the normal onload callback but if I want to do it on a define function, it fails.
May I know what is the mistakes and How to do it? Below are the codes,
function ajax (url, method) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = onloadUpdate();
//xhr.send(data)
}
function onloadUpdate () {
console.log(this.responseText);
// the result is undefined
// other codes for success update notification
}
ajax('sample-site.dev', 'POST');

Javascript return array through http request

I am opening a PHP file with http request:
// Load PHP File for Ajax
function downloadUrl(url, callback) {
var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
However, that (url) will be returning an array as so in PHP:
return array(
'xml' => $googleMaps->generateXML($results),
'results' => $googleMaps->getResults()
);
So when I call the function as so:
// generate xml and markup map
downloadUrl(searchURL, function(data) {
var xml = parseXml(data);
}
I want to be able to distinguish between the xml and results indexes in the array. I return it as data. I'm just confused on how to parse just the xml and not the entire array.

javascript XMLHttpRequest requestXML is null

I'm trying to grab an xml document from a url and then parse it. I am able to open it fine on a browser, but it doesnt seem to work through my javascript. Can anyone help me?
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = function(){};
callback(request, request.status);
}
};
request.open('GET', "url", true);
request.send(null);
}
downloadUrl("http://jojo.theone.net/survey.xml", function(data) {
alert("Inside downloadURL"); // shows up
var xml = request.responseXML;
alert(xml); // Doesn't even show up.
alert(request.responseText); // Doesnt show up.
});
You are using data as the parameter name in your callback method, but calling the callback method as callback(request, request.status). The result is that the request object is now in the var called "data", and the request.status is not referenced at all.
Try
downloadUrl("http://jojo.theone.net/survey.xml", function(request, status) {
alert("Inside downloadURL");
var xml = request.responseXML;
alert(xml);
alert(request.responseText);
});
Try to use data value not the request object. Also it is better to use some framework like Mootools or jQuery to perform AJAX requests -- you'll get a more compatible and predictable interface.
Also note that request will fail if the url you're requesting has different server, port and protocol than the script that is making request.

How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?

I'm looking on the web, but documentation is hard to come by. We all know the basic AJAX call using the browser's built-in XMLHttpRequest object (assume a modern browser here):
var xmlHttp = new XMLHttpRequest(); // Assumes native object
xmlHttp.open("GET", "http://www.example.com", false);
xmlHttp.send("");
var statusCode = xmlHttp.status;
// Process it, and I'd love to know if the request timed out
So, is there a way that I can detect that the AJAX call timed out by inspecting the XMLHttpRequest object in the browser? Would I be advised to do something like window.setTimeout(function() { xmlHttp.abort() }, 30000);?
Thanks!
-Mike
Some of the modern browsers (2012) do this without having to rely on setTimeout: it's included in the XMLHttpRequest. See answer https://stackoverflow.com/a/4958782/698168:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert("ready state = 4");
}
};
xhr.open("POST", "http://www.service.org/myService.svc/Method", true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.timeout = 4000;
xhr.ontimeout = function () { alert("Timed out!!!"); }
xhr.send(json);
UPDATE: Here's an example of how you can handle a timeout:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://www.example.com", true);
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
clearTimeout(xmlHttpTimeout);
alert(xmlHttp.responseText);
}
}
// Now that we're ready to handle the response, we can make the request
xmlHttp.send("");
// Timeout to abort in 5 seconds
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
xmlHttp.abort();
alert("Request timed out");
}
In IE8, You can add a timeout event handler to the XMLHttpRequest object.
var xmlHttp = new XMLHttpRequest();
xmlHttp.ontimeout = function(){
alert("request timed out");
}
I would recommend against making synchronous calls as your code implies and also recommend using a javascript framework to do this. jQuery is the most popular one. It makes your code more efficient, easier to maintain and cross-browser compatible.

Categories

Resources