DOJO/Ajax: Dynamic Loading of Content & DOJO Upgrade - ajax

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

Related

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.

Json result returned as a file in Internet Explorer?

net MVC application, in which I have multiple charts. On these charts, I have applied filters and by clicking each filter, I do an ajax call which returns the result in Json and then applies to the charts.
Now its working perfectly in Firefox and Chrome, but in Internet Explorer - Ajax call is always unsuccessful. I tried hitting the web api url directly through my browser and the issue it seems is, the result json was being returned as a file to be downloaded.
This is my ajax code :
function getIssueResolvedGraphdata(control, departCode, departName) {
$.ajax(
{
type: "GET",
url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (myData) {
var resolvedStartDate = myData.data.IssueResolvedStartDate;
var issueData = myData.data.IssueData;
var resolveData = myData.data.ResolvedData;
//converting issueData into integer array...
var issue = issueData.replace("[", "");
var issue1 = issue.replace("]", "");
var issue2 = issue1.split(",");
for (var i = 0; i < issue2.length; i++) { issue2[i] = parseInt(issue2[i]); }
//converting resolvedData into integer array
var resolve = resolveData.replace("[", "");
var resolve1 = resolve.replace("]", "");
var resolve2 = resolve1.split(",");
for (var j = 0; j < resolve2.length; j++) { resolve2[j] = parseInt(resolve2[j]); }
//getting max value from array...
var issueMaxVal = Math.max.apply(null, issue2);
var resolveMaxVal = Math.max.apply(null, resolve2);
//Eliminating leading zeros in issue array
var removeIndex = 0;
var myDate;
var newDate;
var arrayLength;
if (issueMaxVal != 0) {
arrayLength = issue2.length;
for (var i = 0; i < arrayLength; i++) {
if (issue2[0] == 0) {
issue2.splice(0, 1);
removeIndex = i;
} else {
break;
}
}
//Getting days count of current month
var monthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
var monthEnd = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1);
var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
var monthDays = 0;
if (monthLength == 28) {
monthDays = removeIndex;
}
else if (monthLength == 30) {
monthDays = removeIndex + 1;
}
else if (monthLength == 31 || monthLength == 29) {
monthDays = removeIndex + 2;
}
//matching the resultant issue array with resolve array & setting start date
var iDate = resolvedStartDate;
var tDate = '';
for (var i = 0; i < iDate.length; i++) {
if (iDate[i] == ',') {
tDate += '/';
}
else {
tDate += iDate[i];
}
}
if (removeIndex != 0) {
resolve2.splice(0, (removeIndex + 1));
var myDate = new Date(tDate);
myDate.setDate(myDate.getDate() + monthDays);
newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
} else {
var myDate = new Date(tDate);
newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
}
} else {
alert("Empty");
}
//updating chart here...
var chart = $('#performance-cart').highcharts();
chart.series[0].update({
pointStart: newDate,
data: issue2
});
chart.series[1].update({
pointStart: newDate,
data: resolve2
});
if (issueMaxVal > resolveMaxVal) {
chart.yAxis[0].setExtremes(0, issueMaxVal);
} else {
chart.yAxis[0].setExtremes(0, resolveMaxVal);
}
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
} });}
Code from web api controller :
[HttpGet]
[CrossDomainActionFilter]
public Response<GraphIssueResolvedWrapper> GetQueryIssueResolvedData(string deptCode)
{
Response<GraphIssueResolvedWrapper> objResponse = new Response<GraphIssueResolvedWrapper>();
GraphIssueResolvedWrapper objGraphIssueResolvedWrapper = new GraphIssueResolvedWrapper();
try
{
....code.....
objResponse.isSuccess = true;
objResponse.errorDetail = string.Empty;
objResponse.data = objGraphIssueResolvedWrapper;
}
catch (Exception ex)
{
objResponse.isSuccess = false;
objResponse.errorDetail = ex.Message.ToString();
objResponse.data = null;
}
return objResponse;
}
Reponse Class :
public class Response<T>
{
public bool isSuccess { get; set; }
public string errorDetail { get; set; }
public T data { get; set; }
}
I am stuck at this for hours now. Any help will be appreciated.
I have solved my problem by using the following code : ( I guess it needed CORS support)
function isIE() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE");
if (msie > 0)
return true;
return false;
}
Then in document.ready function of my binding script :
$(document).ready(function () {
if (isIE())
$.support.cors = true;
});
Note : it still download Json stream as a file but now my AJAX call is successful upon each hit.
You've missed contentType: 'text/html' which is pretty important for IE7-8:
$.ajax(
{
type: "GET",
url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
dataType: "json",
contentType: 'text/html'
crossDomain: true,
async: true,
cache: false,
success: function (myData) {
var result = JSON.parse(myData);
///...code...
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
}
}
);
To make it works in IE7-8 you also need to be sure that you've writing Conrent-Type Header into your response on server side. Add this line right before return statement;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html; charset=iso-8859-1");
And in code probably you will need to parse result in success method by using JSON.parse(myData);

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

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
}

Error in jquery.handleErrors when using IE

I use this AJAX jQuery plugin in our site. When I test it using IE, I'm getting this error ( Object doesn't support property or method 'handleError') that pertains to this line:
jQuery.handleError(s, xml, null, e);
I'm using 1.7.1 version of jQuery. How can I replace it?
Here's the full code
jQuery.extend({
createUploadIframe: function (id, uri) {
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if (window.ActiveXObject) {
if (typeof uri == 'boolean') {
iframeHtml += ' src="' + 'javascript:false' + '"';
} else if (typeof uri == 'string') {
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function (id, fileElementId, data) {
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if (data) {
for (var i in data) {
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function (s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data));
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if (s.global && !jQuery.active++) {
jQuery.event.trigger("ajaxStart");
}
var requestDone = false;
// Create the request object
var xml = {}
if (s.global) jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function (isTimeout) {
var io = document.getElementById(frameId);
try {
if (io.contentWindow) {
xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
} else if (io.contentDocument) {
xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
}
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
if (xml || isTimeout == "timeout") {
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if (status != "error") {
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData(xml, s.dataType);
// If a local callback was specified, fire it and pass it the data
if (s.success) s.success(data, status);
// Fire the global callback
if (s.global) jQuery.event.trigger("ajaxSuccess", [xml, s]);
} else jQuery.handleError(s, xml, status);
} catch (e) {
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if (s.global) jQuery.event.trigger("ajaxComplete", [xml, s]);
// Handle the global AJAX counter
if (s.global && !--jQuery.active) jQuery.event.trigger("ajaxStop");
// Process result
if (s.complete) s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function () {
try {
jQuery(io).remove();
jQuery(form).remove();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if (s.timeout > 0) {
setTimeout(function () {
// Check to see if the request is still happening
if (!requestDone) uploadCallback("timeout");
}, s.timeout);
}
try {
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if (form.encoding) {
jQuery(form).attr('encoding', 'multipart/form-data');
} else {
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback);
return {
abort: function () {}
};
},
uploadHttpData: function (r, type) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if (type == "script") jQuery.globalEval(data);
// Get the JavaScript object, if JSON is used.
if (type == "json") eval("data = " + data);
// evaluate scripts within html
if (type == "html") jQuery("<div>").html(data).evalScripts();
return data;
}
})
handleError was removed from jQuery in 1.5. Are you sure it's working in firefox etc.?
See: When was handleError removed from jQuery?

Resources