Control flow with XmlHttpRequest? - ajax

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);
}
}
}
}

Related

send two ajax requests one after another

im working on an HTML5 project that uses multiple canvases,
after the user finishes drawing using the canvas i save them as images to the server.
this is what i have:
function saveViaAJAX()
{
$("#dvloader").show();
document.getElementById("search-result").innerHTML="saving first image...";
var saveCanvasFront = document.getElementById("collage-front");
var canvasDataFront = saveCanvasFront.toDataURL("image/png");
var postDataFront = "canvasData="+canvasDataFront;
var debugConsole= document.getElementById("search-result");
var saveCanvasBack = document.getElementById("collage-back");
var canvasDataBack = saveCanvasBack.toDataURL("image/png");
var postDataBack = "canvasData="+canvasDataBack;
var ajax = new XMLHttpRequest();
ajax.open("POST",'index.php?option=com_canvas&format=raw&task=savecanvas',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
var ajax2 = new XMLHttpRequest();
ajax2.open("POST",'index.php?option=com_canvas&format=raw&task=savecanvas',true);
ajax2.setRequestHeader('Content-Type', 'canvas/upload');
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
document.getElementById("search-result").innerHTML="saving second image..";
ajax2.send(postDataBack);
}
}
ajax2.onreadystatechange=function()
{
if (ajax2.readyState == 4)
{
document.getElementById("search-result").innerHTML="canvases saved successfully";
setTimeout('top.location.href="index.php"', 4000)
$("#dvloader").hide();
}
}
ajax.send(postDataFront);
}
im sure there is a more elegant way to achieve this. i just want to make sure both requests are successful.this is why im calling them serially, one after the other.
is this correct ?
Thanks
this worked for me
// JavaScript Document
function saveViaAJAX()
{
if(some condition){
alert("false");
return false;
} else {
if (confirm('confirm')) {
callAjax();
}
}
}
function callAjax(){
document.getElementById("process").innerHTML="processing...";
ajax0();
}
function ajax0()
{
var postData = "";
var ajax = new XMLHttpRequest();
ajax.open("POST",'index.php?....',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
document.getElementById("process").innerHTML="next process...";
ajax1();
}
}
ajax.send(postData);
}
function ajax1()
{
var ajax = new XMLHttpRequest();
ajax.open("POST",'index.php?...',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
if (ajax.status==403){
document.getElementById("process").innerHTML="error: " + ajax.status + " retry...";
setTimeout( ajax1(), 3000 );
} else if (ajax.status==200 || window.location.href.indexOf("http")==-1 || ajax.responseText != 'failed'){
document.getElementById("process").innerHTML="processing...";
ajax2();
} else {
document.getElementById("process").innerHTML="error: " + ajax.status;
}
}
}
ajax.send(postData);
}
function ajax2()
{
var canvasData = saveCanvas.toDataURL("image/png");
var postData = "canvasData="+canvasData;
var ajax = new XMLHttpRequest();
ajax.open("POST",'index.php?...',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
if (ajax.status==403){
document.getElementById("search-result").innerHTML="error: " + ajax.status + " retrying...";
setTimeout( ajax2(), 3000 );
} else if (ajax.status==200 || window.location.href.indexOf("http")==-1 || ajax.responseText != 'failed'){
document.getElementById("search-result").innerHTML="processing....";
ajax3();
} else {
document.getElementById("search-result").innerHTML="error: " + ajax.status;
}
}
}
ajax.send(postData);
}
function ajax3()
{
var postData = "";
var ajax = new XMLHttpRequest();
ajax.open("POST",'index.php?...',true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
if (ajax.status==403){
document.getElementById("search-result").innerHTML="error: " + ajax.status +
" retrying...";
setTimeout( ajax3(), 3000 );
} else if (ajax.status==200 || window.location.href.indexOf("http")==-1 || ajax.responseText != 'failed'){
document.getElementById("process").innerHTML="success";
}
else{
document.getElementById("process").innerHTML="error:" + ajax.status ;
}
}
}
ajax.send(postData);
}
write both ajax request to two functions. call those functions in the main like this.
fun main(){
//read the canvas code
ajax1();
ajax2();
}
fun ajax1(){
//your call
}
fun ajax2(){
//your call
}

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.

How to use AJAX in Dart with async = true

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);

Returning the responseText from ajax function

See the following function I have written
The code is to receive a url and send data to that page in post/get method.The function returns responseText from the target page
function $send(url,data,method)
{
if(window.XMLHttpRequest)
var connect = new XMLHttpRequest();
else
var connect = newActiveXObject("Microsoft.XMLHTTP");
if(connect)
{
method = method.toUpperCase();
if(method == 'GET')
{
url += '?'+data;
connect.open(method,url,true);
connect.send();
}
else
{
connect.setRequestHeader("Content-type","application/x-www-form-urlencoded");
connect.open(method,url,true);
connect.send(data);
}
connect.onreadystatechange = function()
{
alert(connect.readyState);
if(connect.readyState==4 &&connect.status == 200)
{
return connect.responseText ;
}
}
return "FALSE";
}
else
{
alert("$sendData() is not supported by your browser\n\nTRY ANOTHER BROWSER!!!");
return "FALSE";
}
}
As readstate is initially 0 and changes eventually,my function always return FALSE.Is there any way to return the responseText

Firefox, Mozilla validator error

I am getting this one error when I use the Mozilla validator:
This is the JS file:
const STATE_START = Components.interfaces.nsIWebProgressListener.STATE_START;
const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;
// Version changes:
// It used to get the lists from a PHP file, but that was putting too much of a strain on the servers
// now it uses xml files.
// Randomizes the servers to load balance
// Mozilla editor suggested no synchronous file gets, so changed it to asynchronous
// Added one more server to help with the updates (Ilovemafiaafire.net)
// Edited some redirect code that some idiots were spreading FUD about.
var xmlDoc = null;
var quickFilter_100_count_redirect_url='http://www.mafiaafire.com/help_us.php';
var countXmlUrl = 0;
//var xmlUrl = 'http://elxotica.com/xml-update/xml-list.php';
var xmlUrl = new Array(4);
xmlUrl[0] = 'http://mafiaafire.com/xml-update/mf_xml_list.xml';
xmlUrl[1] = 'http://ifucksexygirls.com/xml-update/mf_xml_list.xml';
xmlUrl[2] = 'http://ezee.se/xml-update/mf_xml_list.xml';
xmlUrl[3] = 'http://ilovemafiaafire.net/mf_xml_list.xml';
xmlUrl.sort(function() {return 0.5 - Math.random()})
var realXmlUrl = xmlUrl[countXmlUrl];
var notificationUrl = 'http://mafiaafire.com/xml-update/click_here_for_details.php';
var root_node = null;
var second_node = null;
var timervar = null;
var mafiaafireFilterUrl = '';
//Calling the interface for preferences
var prefManager = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
var quickfilter_mafiaafire =
{
// get the domain name from the current url
get_domain_name:function()
{
var urlbar = window.content.location.href;
domain_name_parts = urlbar.match(/:\/\/(.[^/]+)/)[1].split('.');
if(domain_name_parts.length >= 3){
domain_name_parts[0] = '';
}
var dn = domain_name_parts.join('.');
if(dn.indexOf('.') == 0)
return dn.substr(1);
else
return dn;
},
// send ajax request to server for loading the xml
request_xml:function ()
{
//alert(countXmlUrl);
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
if (!http_request)
{
return false;
}
http_request.onreadystatechange = this.response_xml;
http_request.open('GET', realXmlUrl, true);
http_request.send(null);
xmlDoc = http_request.responseXML;
},
// receive the ajax response
response_xml:function ()
{
if (http_request.readyState == 4)
{
if(http_request.status == 404 && countXmlUrl<=3)
{
countXmlUrl++;
//alert(xmlUrl[countXmlUrl]);
realXmlUrl = xmlUrl[countXmlUrl];
quickfilter_mafiaafire.request_xml();
}
if (http_request.status == 200)
{
xmlDoc = http_request.responseXML;
}
}
},
filterUrl:function()
{
var urlBar = window.content.location.href;
//check if url bar is blank or empty
if (urlBar == 'about:blank' || urlBar == '' || urlBar.indexOf('http')<0)
return false;
//1. get domain
processing_domain = this.get_domain_name();
//alert(processing_domain);
//Couldn't fetch the XML config, so returning gracefully
if(xmlDoc == null)
return false;
try
{
root_node = '';
// Parsing the xml
root_node = xmlDoc.getElementsByTagName('filter');
for(i=0;i<=root_node.length;i++)
{
second_node = '';
second_node = root_node[i];
if(second_node.getElementsByTagName('realdomain')[0].firstChild.nodeValue == processing_domain)
{
this.notificationBox();
mafiaafireFilterUrl = '';
mafiaafireFilterUrl = second_node.getElementsByTagName('filterdomain')[0].firstChild.nodeValue;
timervar = setTimeout("quickfilter_mafiaafire.redirectToAnotherUrl()",1500);
//window.content.location.href = second_node.getElementsByTagName('filterdomain')[0].firstChild.nodeValue;
//this.redirectToAnotherUrl(this.filterUrl);
//timervar = setInterval("quickfilter_mafiaafire.redirectToAnotherUrl(quickfilter_mafiaafire.filterUrl)",1000);
}
}
}
catch(e){
//alert(e.toString());
}
},
// This function is called for showing the notification
notificationBox:function()
{
try{
// Firefox default notification interface
var notificationBox = gBrowser.getNotificationBox();
notificationBox.removeAllNotifications(false);
notificationBox.appendNotification('You are being redirected', "", "chrome://quickfilter/content/filter.png", notificationBox.PRIORITY_INFO_HIGH, [{
accessKey: '',
label: ' click here for details',
callback: function() {
// Showing the notification Bar
window.content.location.href = notificationUrl;
}
}]);
}catch(e){}
},
redirectToAnotherUrl:function()
{
var qucikFilterRedirectCount = '';
//Read the value from preferrences
qucikFilterRedirectCount = prefManager.getCharPref("extensions.quickfilter_redirect_count");
//alert(qucikFilterRedirectCount);
if(qucikFilterRedirectCount % 15 == 0)
{
// Disable for now, can comment this entire section but this is the easier fix incase we decide to enable it later
//window.content.location.href = quickFilter_100_count_redirect_url+"?d="+mafiaafireFilterUrl;
window.content.location.href = mafiaafireFilterUrl;
}
else
{
window.content.location.href = mafiaafireFilterUrl;
}
qucikFilterRedirectCount = parseInt(qucikFilterRedirectCount)+1;
prefManager.setCharPref("extensions.quickfilter_redirect_count",qucikFilterRedirectCount);
}
}
var quickfilter_urlBarListener = {
QueryInterface: function(aIID)
{
if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
aIID.equals(Components.interfaces.nsISupports))
return this;
throw Components.results.NS_NOINTERFACE;
},
//Called when the location of the window being watched changes
onLocationChange: function(aProgress, aRequest, aURI)
{
// This fires when the location bar changes; that is load event is confirmed
// or when the user switches tabs. If you use myListener for more than one tab/window,
// use aProgress.DOMWindow to obtain the tab/window which triggered the change.
quickfilter_mafiaafire.filterUrl();
},
//Notification indicating the state has changed for one of the requests associated with aWebProgress.
onStateChange: function(aProgress, aRequest, aFlag, aStatus)
{
if(aFlag & STATE_START)
{
// This fires when the load event is initiated
}
if(aFlag & STATE_STOP)
{
// This fires when the load finishes
}
},
//Notification that the progress has changed for one of the requests associated with aWebProgress
onProgressChange: function() {},
//Notification that the status of a request has changed. The status message is intended to be displayed to the user.
onStatusChange: function() {},
//Notification called for security progress
onSecurityChange: function() {},
onLinkIconAvailable: function() {}
};
var quickfilter_extension = {
init: function()
{
//Initiating the progressListerner
gBrowser.addProgressListener(quickfilter_urlBarListener, Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
//Load the block list xml form server
quickfilter_mafiaafire.request_xml();
},
uninit: function()
{
// Remove the progressListerner
gBrowser.removeProgressListener(quickfilter_urlBarListener);
}
};
// window.addEventListener("load", function () { TheGreatTest1.onFirefoxLoad(); }, false);
// this function is Called on window Onload event
window.addEventListener("load", function(e) {
quickfilter_extension.init();
}, false);
window.addEventListener("unload", function(e) {
quickfilter_extension.uninit();
}, false);
Can you tell me how to squash that error please?
It looks like the offending line is setTimeout("quickfilter_mafiaafire.redirectToAnotherUrl()",1500);
The setTimeout function can take a string (which then essentially gets eval'd) or a function (which gets called). Using a string is not recommended, for all the same reasons that using eval is not recommended. See https://developer.mozilla.org/en/DOM/window.setTimeout
In this case, the simplest fix would be to change it to setTimeout(function() { quickfilter_mafiaafire.redirectToAnotherUrl(); },1500);

Resources