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?
Related
I'd like to convert following HTML(json, ajax) Code in C# Winform application.
I'll try it by using JSON.Net, but I'm not familiar with C# WinForm.
I want to binding ajax result value after the user click a button.
How do I this??
html code following that :
Thank you.
// format string
function J2String(object) {
var results = [];
for (var property in object) {
var value = object[property];
if (value != null){
results.push(property.toString() + ': ' + value );
}
}
return '{' + results.join(', ') + '}';
}
// format ajax result data
formatstring = function (text) {
if (arguments.length <= 1) return text;
for (var i = 0; i <= arguments.length - 2; i++) {
text = text.replace(new RegExp("\\{" + i + "\\}", "gi"),
arguments[i + 1]);
}
return text;
}
// return data [ GET method ]
function GetAjaxData(){
RcvData.value = "";
$.ajax({
url:"http://127.0.0.1",
type:"GET",
data: { "REQ": formatstring ("AA^^1000^^^^23^1234567^W1234567890^^00000081") },
dataType: "jsonp",
jsonp: "callback",
success: function(data){
RcvData.value = J2String(data);
}
});
}
<body>
Value : <input type="text" style="width:80%" id="RcvData"><br/>
<form name="tform" method="post">
<input type="button" value="Send" onClick="GetAjaxData()" >
</body>
[ .net framework 4.5 ]
~~~ using ~~ ;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
private async void btnTest_Click(object sender, EventArgs e){
string reqData = "AA^^1000^^^^23^1234567^W1234567890^^00000081";
textBox1.Text = await GetAjaxData(reqData);
}
private async Task<string> GetAjaxData(string reqData){
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost/?callback=jsonp123456&REQ=" + reqData );
response.EnsureSuccessStatusCode();
byte[] buf = await response.Content.ReadAsByteArrayAsync();
Encoding myEncoding = Encoding.GetEncoding("utf-8");
string data = myEncoding.GetString(buf, 0, buf.Length - 1);
dynamic obj = JsonConvert.DeserializeObject(data );
string _parseData = obj.Code
+ "^" + obj.Name
+ "^" + obj.RespCode
+ "^" + obj.Remark;
var result = await Task.FromResult<string>(_parseData);
return result;
}
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];
}
})();
I'm performing AJAX using the following code:
function main() {
// get the name fields
var name1 = document.getElementById("name1").value;
var name2 = document.getElementById("name2").value;
// Encode the user's input as query parameters in a URL
var url = "response.php" +
"?name1=" + encodeURIComponent(name1) +
"&name2=" + encodeURIComponent(name2);
// Fetch the contents of that URL using the XMLHttpRequest object
var req = createXMLHttpRequestObject();
req.open("GET", url);
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
try {
// If we get here, we got a complete valid HTTP response
var response = req.responseText; // HTTP response as a string
var text = JSON.parse(response); // Parse it to a JS array
// Convert the array of text objects to a string of HTML
var list = "";
for (var i = 0; i < text.length; i++) {
list += "<li><p>" + text[i].reply + " " + text[i].name + "</p>";
}
// Display the HTML in the element from above.
var ad = document.getElementById("responseText");
ad.innerHTML = "<ul>" + list + "</ul>";
} catch (e) {
// display error message
alert("Error reading the response: " + e.toString());
}
} else {
// display status message
alert("There was a problem retrieving the data:\n" + req.statusText);
}
}
req.send(null);
}
// creates an XMLHttpRequest instance
function createXMLHttpRequestObject() {
// xmlHttp will store the reference to the XMLHttpRequest object
var xmlHttp;
// try to instantiate the native XMLHttpRequest object
try {
// create an XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
} catch (e) {
// assume IE6 or older
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
} catch (e) {}
}
// return the created object or display an error message
if (!xmlHttp) alert("Error creating the XMLHttpRequest object.");
else return xmlHttp;
}
This works exactly as planned, the code within the try block is executed perfectly. But the alert "There was a problem retrieving the data: is also activated, with req.statusText displaying "OK".
How can this be possible? How can the code within the if statement activate perfectly but at the same time the else block is activated?
I'm stumped, any ideas?
The servor code is simply:
<?php
if( $_GET["name1"] || $_GET["name2"] ) {
$data = array(
array('name' => $_GET["name1"], 'reply' => 'hello'),
array('name' => $_GET["name2"], 'reply' => 'bye'),
);
echo json_encode($data);
}
?>
And the HTML:
<input id="name1">
<input id="name2">
<div id="responseText"></div>
<button onclick="main();">Do Ajax!</button>
Your conditional is probably being activated when req.readyState == 3 (content has begun to load). The onreadystatechange method may be triggered multiple times on the same request. You only care about what happens when it's 4, so refactor your method to only test when that is true:
var req = createXMLHttpRequestObject();
req.open("GET", url);
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
try {
// If we get here, we got a complete valid HTTP response
var response = req.responseText; // HTTP response as a string
var text = JSON.parse(response); // Parse it to a JS array
// Convert the array of text objects to a string of HTML
var list = "";
for (var i = 0; i < text.length; i++) {
list += "<li><p>" + text[i].reply + " " + text[i].name + "</p>";
}
// Display the HTML in the element from above.
var ad = document.getElementById("responseText");
ad.innerHTML = "<ul>" + list + "</ul>";
} catch(e) {
// display error message
alert("Error reading the response: " + e.toString());
}
} else {
// display status message
alert("There was a problem retrieving the data:\n" + req.statusText);
}
}
};
req.send(null);
I'm trying to make an AJAX request to a public service
Here's the code:
$.ajax({
url : "http://api.geonames.org/citiesJSON",
type : 'POST',
cache : false,
dataType : 'json',
data : {
username: "demo",
north:10,
south: 10,
east:10,
west:10}
}).done(function(data) {
alert("Success: " + JSON.stringify(data));
}).fail(function(a, b, c, d) {
alert("Failure: "
+ JSON.stringify(a) + " "
+ JSON.stringify(b) + " "
+ JSON.stringify(c) + " "
+ JSON.stringify(d) );
});
You may try it in this link: http://jsfiddle.net/hDXq3/
The response is retrieved successfully on Chrome & Firefox, and the output is as follows:
But for IE, the fails alerting:
Failure: {"readyState":0,"status":0,"statusText":"No Transport"} "error" "No Transport" undefined
Why it's not working on IE ? and how to fix this ?
Here's the solution for those who are interested:
if (!jQuery.support.cors && window.XDomainRequest) {
var httpRegEx = /^https?:\/\//i;
var getOrPostRegEx = /^get|post$/i;
var sameSchemeRegEx = new RegExp('^'+location.protocol, 'i');
var xmlRegEx = /\/xml/i;
// ajaxTransport exists in jQuery 1.5+
jQuery.ajaxTransport('text html xml json', function(options, userOptions, jqXHR){
// XDomainRequests must be: asynchronous, GET or POST methods, HTTP or HTTPS protocol, and same scheme as calling page
if (options.crossDomain && options.async && getOrPostRegEx.test(options.type) && httpRegEx.test(userOptions.url) && sameSchemeRegEx.test(userOptions.url)) {
var xdr = null;
var userType = (userOptions.dataType||'').toLowerCase();
return {
send: function(headers, complete){
xdr = new XDomainRequest();
if (/^\d+$/.test(userOptions.timeout)) {
xdr.timeout = userOptions.timeout;
}
xdr.ontimeout = function(){
complete(500, 'timeout');
};
xdr.onload = function(){
var allResponseHeaders = 'Content-Length: ' + xdr.responseText.length + '\r\nContent-Type: ' + xdr.contentType;
var status = {
code: 200,
message: 'success'
};
var responses = {
text: xdr.responseText
};
try {
if (userType === 'json') {
try {
responses.json = JSON.parse(xdr.responseText);
} catch(e) {
status.code = 500;
status.message = 'parseerror';
//throw 'Invalid JSON: ' + xdr.responseText;
}
} else if ((userType === 'xml') || ((userType !== 'text') && xmlRegEx.test(xdr.contentType))) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = false;
try {
doc.loadXML(xdr.responseText);
} catch(e) {
doc = undefined;
}
if (!doc || !doc.documentElement || doc.getElementsByTagName('parsererror').length) {
status.code = 500;
status.message = 'parseerror';
throw 'Invalid XML: ' + xdr.responseText;
}
responses.xml = doc;
}
} catch(parseMessage) {
throw parseMessage;
} finally {
complete(status.code, status.message, responses, allResponseHeaders);
}
};
xdr.onerror = function(){
complete(500, 'error', {
text: xdr.responseText
});
};
xdr.open(options.type, options.url);
//xdr.send(userOptions.data);
xdr.send();
},
abort: function(){
if (xdr) {
xdr.abort();
}
}
};
}
});
};
jQuery.support.cors = true;
$.ajax({
url : "http://api.geonames.org/citiesJSON",
crossDomain: true,
type : 'POST',
cache : false,
dataType : 'json',
data : {
username: "demo",
north:10,
south: 10,
east:10,
west:10}
}).done(function(data) {
alert("Success: " + JSON.stringify(data));
}).fail(function(a, b, c, d) {
alert("Failure: "
+ JSON.stringify(a) + " "
+ JSON.stringify(b) + " "
+ JSON.stringify(c) + " "
+ JSON.stringify(d) );
});
You may try it in this link: http://jsfiddle.net/bjW8t/4/
Just include the jQuery ajaxTransport extension that uses XDomainRequest for IE8+.
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
}