send two ajax requests one after another - ajax

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
}

Related

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

How to read cookie in nsIChannel?

const {Cc,Ci,Cr} = require("chrome");
function TracingListener() {
//this.receivedData = [];
}
function CCIN(cName, ifaceName) {
return Cc[cName].createInstance(Ci[ifaceName]);
}
function CCSV(cName, ifaceName){
if (Cc[cName])
// if fbs fails to load, the error can be _CC[cName] has no properties
return Cc[cName].getService(Ci[ifaceName]);
};
TracingListener.prototype =
{
originalListener: null,
receivedData: null, // array for incoming data.
onDataAvailable: function(request, context, inputStream, offset, count)
{
this.originalListener.onDataAvailable(request, context,inputStream, offset, count);
},
onStartRequest: function(request, context) {
this.receivedData = [];
this.originalListener.onStartRequest(request, context);
//thechannel.setRequestHeader("X-Hello", "World", false);
//this part of code will stop the request
/*request.QueryInterface(Ci.nsIHttpChannel);
var cookie=request.getRequestHeader("Cookie");
console.log("cookie="+cookie);*/
var postText = this.readPostTextFromRequest(request, context);
console.log("postText="+postText111);
},
onStopRequest: function(request, context, statusCode)
{
//this part of code will successfullly print the cookie
/*request.QueryInterface(Ci.nsIHttpChannel);
var cookie=request.getRequestHeader("Cookie");
console.log("cookie="+cookie);*/
this.originalListener.onStopRequest(request, context, statusCode);
},
QueryInterface: function (aIID) {
if (aIID.equals(Ci.nsIStreamListener) ||
aIID.equals(Ci.nsISupports)) {
return this;
}
throw Cr.NS_NOINTERFACE;
},
readPostTextFromRequest : function(request, context) {
try
{
var is = request.QueryInterface(Ci.nsIUploadChannel).uploadStream;
if (is)
{
var ss = is.QueryInterface(Ci.nsISeekableStream);
var prevOffset;
if (ss)
{
prevOffset = ss.tell();
ss.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
}
// Read data from the stream..
var charset = "UTF-8";
var text = this.readFromStream(is, charset, true);
// Seek locks the file so, seek to the beginning only if necko hasn't read it yet,
// since necko doesn't seek to 0 before reading (at lest not till 459384 is fixed).
if (ss && prevOffset == 0)
ss.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
return text;
}
else {
//dump("Failed to Query Interface for upload stream.\n");
}
}
catch(exc)
{
//dumpError(exc);
}
return null;
},
readFromStream : function(stream, charset, noClose) {
var sis = CCSV("#mozilla.org/binaryinputstream;1", "nsIBinaryInputStream");
sis.setInputStream(stream);
var segments = [];
for (var count = stream.available(); count; count = stream.available())
segments.push(sis.readBytes(count));
if (!noClose)
sis.close();
var text = segments.join("");
return text;
}
}
hRO = {
observe: function(request, aTopic, aData){
try {
if (aTopic == "http-on-examine-response") {
request.QueryInterface(Ci.nsIHttpChannel);
//if (request.originalURI && piratequesting.baseURL == request.originalURI.prePath && request.originalURI.path.indexOf("/index.php?ajax=") == 0) {
var newListener = new TracingListener();
request.QueryInterface(Ci.nsITraceableChannel);
newListener.originalListener = request.setNewListener(newListener);
//}
}
} catch (e) {
/*dump("\nhRO error: \n\tMessage: " + e.message + "\n\tFile: " + e.fileName + " line: " + e.lineNumber + "\n");*/
}
},
QueryInterface: function(aIID){
if (aIID.equals(Ci.nsIObserver) ||
aIID.equals(Ci.nsISupports)) {
return this;
}
throw Cr.NS_NOINTERFACE;
},
};
var observerService = Cc["#mozilla.org/observer-service;1"]
.getService(Ci.nsIObserverService);
observerService.addObserver(hRO,
"http-on-examine-response", false);
My question is: the same lines of code:
request.QueryInterface(Ci.nsIHttpChannel);
var cookie=request.getRequestHeader("Cookie");
console.log("cookie="+cookie);
performs different results in onStartRequest and onStopRequest, why?
I can read the cookie in onStopRequest but fails in onStartRequest. I don't think the request is not ready in onStartRequest because I can read the postText in onStartRequest.

DOJO/Ajax: Dynamic Loading of Content & DOJO Upgrade

In my application I am expected to show come configurations on UI. Currently appication makes a DOJO call and displays all the configs in UI. But, we are facing time out issues in case of huge configs say 5000 or more, which subsequently takes more time to load the page and application gets timed out since the default time for DOJO is around 3mins.
Solution: We are planning to make subsequent AJAX calls and display 50 rows of configurations at a time. This would mean, that after displaying 50 rows of configs, application will make another AJAX call until all the configs are loaded on the page. This will ensure that DOJO call is not getting timed out. We are planning to move forward with DOJO.xhrGet or DOJO.xhrPost which is a part of request package in DOJO 1.8.
Now, the issue here is that my application is configured with very old version of DOJO. Since, we want to include new request methods which are introduced in DOJO 1.8, what changes will be required here?
We have tried by including the request methods in DOJO.JS but we can see that it impacts other application aspects. Can you please let me know the steps required to include this new package in DOJO.JS?? For reference, please find a snippet of my DOJO.JS.
Any suggestions would be of great help. Thanks!!! :)
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
/*
This is a compiled version of Dojo, built for deployment and not for
development. To get an editable version, please visit:
http://dojotoolkit.org
for documentation and information on getting the source.
*/
if (typeof dojo == "undefined") {
var dj_global = this;
function dj_undef(_1, _2) {
if (_2 == null) {
_2 = dj_global;
}
return (typeof _2[_1] == "undefined");
}
if (dj_undef("djConfig")) {
var djConfig = {};
}
if (dj_undef("dojo")) {
var dojo = {};
}
dojo.version = {major:0,minor:3,patch:1,flag:"",revision:Number("$Rev: 4342 $".match(/[0-9]+/)[0]),toString:function() {
with (dojo.version) {
return major + "." + minor + "." + patch + flag + " (" + revision + ")";
}
}};
dojo.evalProp = function(_3, _4, _5) {
return (_4 && !dj_undef(_3, _4) ? _4[_3] : (_5 ? (_4[_3] = {}) : undefined));
};
dojo.parseObjPath = function(_6, _7, _8) {
var _9 = (_7 != null ? _7 : dj_global);
var _a = _6.split(".");
var _b = _a.pop();
for (var i = 0,l = _a.length; i < l && _9; i++) {
_9 = dojo.evalProp(_a[i], _9, _8);
}
return {obj:_9,prop:_b};
};
dojo.evalObjPath = function(_d, _e) {
if (typeof _d != "string") {
return dj_global;
}
if (_d.indexOf(".") == -1) {
return dojo.evalProp(_d, dj_global, _e);
}
var _f = dojo.parseObjPath(_d, dj_global, _e);
if (_f) {
return dojo.evalProp(_f.prop, _f.obj, _e);
}
return null;
};
dojo.errorToString = function(_10) {
if (!dj_undef("message", _10)) {
return _10.message;
} else {
if (!dj_undef("description", _10)) {
return _10.description;
} else {
return _10;
}
}
};
dojo.raise = function(_11, _12) {
if (_12) {
_11 = _11 + ": " + dojo.errorToString(_12);
}
try {
dojo.hostenv.println("FATAL: " + _11);
}
catch(e) {
}
throw Error(_11);
};
dojo.debug = function() {
};
dojo.debugShallow = function(obj) {
};
dojo.profile = {start:function() {
},end:function() {
},stop:function() {
},dump:function() {
}};
function dj_eval(_14) {
return dj_global.eval ? dj_global.eval(_14) : eval(_14);
}
dojo.unimplemented = function(_15, _16) {
var _17 = "'" + _15 + "' not implemented";
if (_16 != null) {
_17 += " " + _16;
}
dojo.raise(_17);
};
dojo.deprecated = function(_18, _19, _1a) {
var _1b = "DEPRECATED: " + _18;
if (_19) {
_1b += " " + _19;
}
if (_1a) {
_1b += " -- will be removed in version: " + _1a;
}
dojo.debug(_1b);
};
dojo.inherits = function(_1c, _1d) {
if (typeof _1d != "function") {
dojo.raise("dojo.inherits: superclass argument [" + _1d + "] must be a function (subclass: [" + _1c + "']");
}
_1c.prototype = new _1d();
_1c.prototype.constructor = _1c;
_1c.superclass = _1d.prototype;
_1c["super"] = _1d.prototype;
};
dojo.render = (function() {
function vscaffold(_1e, _1f) {
var tmp = {capable:false,support:{builtin:false,plugin:false},prefixes:_1e};
for (var _21 in _1f) {
tmp[_21] = false;
}
return tmp;
}
return {name:"",ver:dojo.version,os:{win:false,linux:false,osx:false},html:vscaffold(["html"], ["ie","opera","khtml","safari","moz"]),svg:vscaffold(["svg"], ["corel","adobe","batik"]),vml:vscaffold(["vml"], ["ie"]),swf:vscaffold(["Swf","Flash","Mm"], ["mm"]),swt:vscaffold(["Swt"], ["ibm"])};
})();
dojo.hostenv = (function() {
var _22 = {isDebug:false,allowQueryConfig:false,baseScriptUri:"",baseRelativePath:"",libraryScriptUri:"",iePreventClobber:false,ieClobberMinimal:true,preventBackButtonFix:true,searchIds:[],parseWidgets:true};
if (typeof djConfig == "undefined") {
djConfig = _22;
} else {
for (var _23 in _22) {
if (typeof djConfig[_23] == "undefined") {
djConfig[_23] = _22[_23];
}
}
}
return {name_:"(unset)",version_:"(unset)",getName:function() {
return this.name_;
},getVersion:function() {
return this.version_;
},getText:function(uri) {
dojo.unimplemented("getText", "uri=" + uri);
}};
})();
dojo.hostenv.getBaseScriptUri = function() {
if (djConfig.baseScriptUri.length) {
return djConfig.baseScriptUri;
}
var uri = new String(djConfig.libraryScriptUri || djConfig.baseRelativePath);
if (!uri) {
dojo.raise("Nothing returned by getLibraryScriptUri(): " + uri);
}
var _26 = uri.lastIndexOf("/");
djConfig.baseScriptUri = djConfig.baseRelativePath;
return djConfig.baseScriptUri;
};
(function() {
var _27 = {pkgFileName:"__package__",loading_modules_:{},loaded_modules_:{},addedToLoadingCount:[],removedFromLoadingCount:[],inFlightCount:0,modulePrefixes_:{dojo:{name:"dojo",value:"src"}},setModulePrefix:function(_28, _29) {
this.modulePrefixes_[_28] = {name:_28,value:_29};
},getModulePrefix:function(_2a) {
var mp = this.modulePrefixes_;
if ((mp[_2a]) && (mp[_2a]["name"])) {
return mp[_2a].value;
}
return _2a;
},getTextStack:[],loadUriStack:[],loadedUris:[],post_load_:false,modulesLoadedListeners:[],unloadListeners:[],loadNotifying:false};
for (var _2c in _27) {
dojo.hostenv[_2c] = _27[_2c];
}
})();

Facebook check in and windows phone

I've got a script that essentially gives the user the ability to check in to a specific location when they click it. Upon clicking it, it checks them into the same location each time.
On desktop this works fine and I suspect it works on Android too. I have a WP and thus obviously I want to get it working on there. This feature is pretty much going to be used exclusively on mobile so getting it working cross-device is important.
Now, to the actual issue. Upon clicking the check in button on WP it loads a blank page and hangs there. Whilst this may be a signal that it perhaps has checked in, when I look it hasn't. So it's hanging there and doing nothing.
This is the URL it's hanging on: https://m.facebook.com/dialog/oauth?display=touch&domain=www.staffscuesociety.com&scope=publish_stream&api_key=API_KEY&app_id=APP_ID&locale=en_US&sdk=joey&access_token=ACCESS_TOKEN&client_id=CLIENT_ID&redirect_uri=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter.php%3Fversion%3D18%23cb%3Df35fef827217048%26origin%3Dhttp%253A%252F%252Fwww.staffscuesociety.com%252Ff166245837c3b6e%26domain%3Dwww.staffscuesociety.com%26relation%3Dopener%26frame%3Df398a7113310e64&origin=2&response_type=token%2Csigned_request
and this is the code:
var button;
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
window.fbAsyncInit = function() {
FB.init({
appId : '260445377421174',
channelUrl : '//www.staffscuesociety.com/checkin/channel.html'
});
button = document.getElementById('checkinWidget');
if (!button) return;
if (!getPost()) {
allowCheckin();
} else {
allowUndo();
}
};
function setPost(value) {
var d = new Date();
d.setDate(d.getTime() + (10 * 60 * 1000));
document.cookie = 'post=' + escape(value) + ';expires=' + d.toUTCString();
}
function getPost() {
return getCookie('post');
}
function getCookie(key) {
currentcookie = document.cookie;
if (currentcookie.length > 0) {
firstidx = currentcookie.indexOf(key + '=');
if (firstidx != -1) {
firstidx = firstidx + key.length + 1;
lastidx = currentcookie.indexOf(';', firstidx);
if (lastidx == -1) {
lastidx = currentcookie.length;
}
return unescape(currentcookie.substring(firstidx, lastidx));
}
}
return '';
}
function checkin() {
allowNothing();
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me/permissions', function (permissions) {
if (permissions.data.length > 0 && permissions.data[0].publish_stream) {
FB.api('/me/feed', 'post', { message: null, place: '117072761683514' }, function(post) {
if (!post || post.error) {
showError();
} else {
setPost(post.id);
allowUndo();
}
});
} else {
allowCheckin();
}
});
} else {
allowCheckin();
}
}, {scope : 'publish_stream'});
}
function undo() {
allowNothing();
FB.api('/' + getPost(), 'delete', function(response) {
setPost('');
allowCheckin();
});
}
function allowNothing() {
button.onclick = function() { };
button.className = 'pressed';
}
function allowCheckin() {
button.onclick = checkin;
button.className = '';
}
function allowUndo() {
button.onclick = undo;
button.className = 'pressed tick';
}
function showError() {
button.className = 'pressed error';
}
}

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