How to use AJAX in Dart with async = true - ajax

I found a reference for an XMLHttpRequest
final req = new XMLHttpRequest();
req.open('GET', '${Sections.home}/data/$name', false);
req.send();
_htmlBody = req.responseText;
Full Source
But this is for async = false, is there a working example of async = true?

There is an example at https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/samples/belay/bcap/bcap_client.dart
void privateInvoke(String ser, String method, String data,
SuccessI ski, FailureI fki) {
if (urlRegex.hasMatch(ser)) {
var req = new XMLHttpRequest();
req.open(method, ser, true);
req.on.readyStateChange.add(void _(evt) {
if (req.readyState == 4) {
if (req.status == 200) {
ski(req.responseText);
} else {
fki(new BcapError(req.status, req.statusText));
}
}
});
req.send(data);
return;
} else {
super.privateInvoke(ser, method, data, ski, fki);
}
}
also another asynchronous example in https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/client/samples/total/src/ServerChart.dart
XMLHttpRequest request = new XMLHttpRequest();
request.on.readyStateChange.add((Event event) {
if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
callback("data:image/png;base64,${StringUtils.base64Encode(request.responseText)}");
}
});
...
request.open("POST", url, true, null, null);
request.setRequestHeader("Content-type", "text/plain");
request.overrideMimeType("text/plain; charset=x-user-defined");
print("Chart request: ${data}");
request.send(data);

Related

How can I send a synchronous ajax request to my server in onunload function

I need to send a ajax request to my server before web page close, my send code is below.
SendByAajx = function(msg) {
var response;
var xmlHttpReg;
if(window.XMLHttpRequest){
xmlHttpReg = new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlHttpReg = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("Unsupported borwser");
}
if(xmlHttpReg != null) {
xmlHttpReg.open("get", "https://127.0.0.1:57688/test"+'?'+msg, false);
xmlHttpReg.send(null);
if(xmlHttpReg.readyState==4){
if(xmlHttpReg.status == 200) {
var data = JSON.parse(xmlHttpReg.responseText);
if(typeof(data.errorcode) == "number" &&
data.errorcode != 0) {
throw("response error:" + data.errorcode);
}
response = data.result;
} else {
throw new Error("Error");
}
}
}
return response;
}
When I call this function in a button onclick event, it works.
function GetOnClick() {
try{
var result = SendByAajx (“data”);
} catch (e) {
//alert(errorInfo);
}
SetButtonDisabled(false);
}
But when I call this function when the page is unloaded, it doesn't work.
<body onload="javascript:OnLoad();" onunload="javascript:OnUnLoad()">
function OnUnLoad() {
try{
var result = SendByAajx(“data”);
} catch (e) {
//alert(errorInfo);
}
}
When I debug the application, the JS execution stops after this line:
xmlHttpReg.send(null);
It didn’t go to the next line:
if(xmlHttpReg.readyState==4)
The “data” is also not sent to the server.
What is wrong with my program, can ajax be called in an onunload function? What should I do to make it work?

callback function wont run when its called

ajax : function(typ,url,callback) {
if(window.XMLHttpRequest) {
var xml = new XMLHttpRequest();
}
if(window.ActiveXObject) {
var xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange = function(callback) {
if(xml.readyState == 4 && xml.status == 200) {
callback();
}
}
xml.open(typ,url,true);
xml.send();
}
}
//Function being called
window.onload = function() {
JS.ajax("GET","/server/chkEmail.php?email=email#email.com",function() {
alert(xml.responseText);
});
}
It throws the error saying:
Uncaught TypeError: callback is not a functionxml.onreadystatechange #
global.js:30
Any ideas?
I fixed it by passing the data variable through the onreadystatechange function and calling it in the callback function.
ajax : function(typ,url,callback) {
if(window.XMLHttpRequest) {
var xml = new XMLHttpRequest();
}
if(window.ActiveXObject) {
var xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange = function(data) {
if(xml.readyState == 4 && xml.status == 200) {
var data = xml.responseText;
callback(data);
}
};
xml.open(typ,url,true);
xml.send();
}
}
window.onload = function() {
JS.ajax("GET","/server/chkEmail.php? email=jonwcode#gmail.com",function(data){
alert(data);
});
}
Try like this:
xml.onreadystatechange = function() {
if (xml.readyState == 4 && xml.status == 200) {
callback();
}
};
Notice that the onreadystatechange function doesn't take any parameters whereas in your code you have passed it a parameter with the name callback which will override the callback variable from the outer scope.
UPDATE:
It looks like you have improperly scoped the xml variable and it isn't available in your AJAX callback. I strongly recommend you reading more about javascript variables scope. Here's how you could make the xml variable visible:
var xml = null;
if (window.XMLHttpRequest) {
xml = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xml = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xml == null) {
alert('Sorry, your browser doesn\'t seem to support AJAX - please upgrade to a modern browser');
} else {
xml.onreadystatechange = function() {
if(xml.readyState == 4 && xml.status == 200) {
var data = xml.responseText;
callback(data);
}
};
xml.open(typ,url,true);
xml.send();
}

Ajax and ActiveXObject

why when I run this code on local server, req.send(sData) doesn't work?
It runs alert1 but doesn't run alert2;
function initialize() {
var req;
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (oc) {
req = null;
}
}
if (!req && typeof XMLHttpRequest != "undefined") {
req = new XMLHttpRequest();
}
return req;
}
function getData(sUrl, sData) {
var req = initialize();
req.open("POST", sUrl, false);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
alert("1");
req.send(sData);
alert("2");
return req.responseText;
}
sUrl and sData are the same as the original website sends.

ajax JSON dump as array

I have a simple ajax script which returns a json dump from the server:
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
function getIslandName() {
var islandGroup = document.getElementById("id_island_group").value;
var url = ".../find_island?island_group=" + escape(islandGroup);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
function updatePage() {
if (request.readyState == 4)
if (request.status == 200)
var data = JSON.decode(request.responseText);
update(data);
//document.getElementById("ajax_response").innerHTML = request.responseText;
else if (request.status == 404)
alert("Request URL does not exist");
else
alert("Error: status code is " + request.status);
}
function update(data) {
for (var key in data) {
alert(data[key]);
}
}
The problem seems to be in the updatePage() function. If I uncomment this line:
//document.getElementById("ajax_response").innerHTML = request.responseText;
the responseText json dump is displayed as expected. e.g.:
["Foo Island", "Bar Island", "Darwin Island"]
Also if I construct a fresh data array within the updatePage() function like so:
function updatePage() {
var string = "Something something ajax";
if (request.readyState == 4)
if (request.status == 200)
var data=new Array();
data[0]="Foo Island";
data[1]="Bar Island";
data[2]="Darwin Island";
update(data);
}
The update() function works as expected and gives the expected alert output.
Any suggestions as to what I'm doing wrong will be much appreciated.

Control flow with XmlHttpRequest?

XmlHttpRequest works through callbacks. So how can I return a value? I tried to set a global variable, but that doesn't seem to be working.
var response = null; // contains the most recent XmlHttpRequest response
// loads the info for this username on the page
function loadUsernameInfo(username) {
getUserInfo(username);
var profile = response;
if (profile) {
// do stuff
}
else {
indicateInvalidUsername(username);
}
}
getUserInfo() can't return a result, because of the callback:
function getUserInfo(username) {
var request = createRequest();
request.onreadystatechange = userObjFromJSON;
var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
var url = "url.php?url=" + twitterURL;
request.open("GET", url, true);
request.send(null);
}
The callback:
function userObjFromJSON() {
if (this.readyState == 4) {
alert(this.responseText);
response = this.responseText;
}
}
How can I get the response back to loadUsernameInfo()?
You can do synchronous requests, though it is not recommended - the A is for Asynchronous... But the general idea to implement this correctly would be:
var response = null; // contains the most recent XmlHttpRequest response
// loads the info for this username on the page
function loadUsernameInfo(username) {
getUserInfo(username, onLoadUsernameComplete);
}
function getUserInfo(username, oncomplete) {
var request = createRequest();
request.__username = username;
request.onreadystatechange = oncomplete;
var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
var url = "url.php?url=" + twitterURL;
request.open("GET", url, true);
request.send(null);
}
function onLoadUsernameComplete(req) {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var profile = req.responseXML;
if (profile) {
// do stuff
}
else {
indicateInvalidUsername(req.__username);
}
}
}
}

Resources