I'm trying to use the code provided by Telerik to add request headers to the XHR, but I'm getting the following error.
"0x800a139e - JavaScript runtime error: InvalidStateError"
Here is the code
$(document).ready(function () {
$("#file").kendoUpload({
multiple: false,
async: {
saveUrl: "save",
},
upload: onUpload,
});
});
function onUpload(e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
xhr.addEventListener("readystatechange", function (e) {
if (xhr.readyState == 1 /* OPENED */) {
xhr.setRequestHeader("X-Foo", "Bar");
}
});
}
}
It turned out that Internet Explorer fires readystatechange twice with readyState 1 and the second execution of the handler causes the error. As a workaround for the the current case you could name the executed handler and unbind it after the first execution.
function onUpload(e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
xhr.addEventListener("readystatechange", function onUploadReady(e) {
if (xhr.readyState == 1 /* OPENED */) {
xhr.setRequestHeader("X-Foo", "Bar");
xhr.removeEventListener("readystatechange", onUploadReady);
}
});
}
}
Related
This issue is literally driving me mad and I've already spent hours researching possible solutions :)
My problem is: I've got a script that, upon loading, makes some AJAX calls to the server. This script is a widget and is already configured for cross-domain , etc.
Everything was working fine until now when 1 request has stopped working. The crazy thing is that is only that one, the others work just fine.
You can see in the screenshot below:
This is the code I use to send AJAX requests:
ajax: {
xhr: null,
request: function (url, method, data, success, failure){
if (!this.xhr){
this.xhr = window.ActiveX ? new ActiveXObject("Microsoft.XMLHTTP"): new XMLHttpRequest();
}
var self = this.xhr;
self.onreadystatechange = function () {
if (self.readyState === 4 && self.status === 200){
success(JSON.parse(self.responseText));
} else if (self.readyState === 4) { // something went wrong but complete
if (failure) {
failure();
} else { console.error("Ajax calls has failed."); }
}
};
self.onerror = function() {
if (failure) {
failure();
} else { console.error("Ajax calls has failed."); }
};
this.xhr.open(method,url,true);
this.xhr.setRequestHeader('Content-Type', 'application/json');
this.xhr.send(JSON.stringify(data));
}
}
And this is the call that causes the problem:
this.ajax.request(
this.getWidgetUrl() +"/check_referral_code",
"POST",
{uuid: SL.uuid, ref_code: ref},
function(data) {
if (data.response == "ok") {
// Do something
} else {
console.error(data.message);
}
},
function(data) {
console.error(data.message);
}
);
Can anybody help here?
UPDATE:
The problem seems to be intermittent. If I reload the page it will literally happen 50% of the times
I use jquery to auto scroll blog post.. They normally works fine but it doesn't scroll or work at all when I load that page via AJAX.. The problem could be how I'm calling ajax to load the page..may be callback function issue which I'm not getting right? here is the ajax code I'm using:
function loadme() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("loadcontent").innerHTML = this.responseText;
}
};
xhttp.open("GET", "http://xxxyyy.com/blogs/", true);
xhttp.send();
}
They all work but jquery post auto scroll will not work.. Is that due to callback function? I'm not sure.. Someone suggest or correct the code... Would appreciate volunteered help
Addition
I did alternative callback function but that too doesn't work either..
<div id="loadcontent"> Content to load/replace</div>
<button onclick="loadDoc('http://xxxyyy.com/blogs', myFunction)">Browse
Blogs</button>
//ajax with callback function
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("loadcontent").innerHTML =
xhttp.responseText;
}
Since you have tagged jquery and you also mentioned jquery in your anwser,
I am providing a jquery solution.
//bind click event to the button, set an id for the button to make it just for that particular button
$(button).click(function() {
ajaxRequest("url", loadcontent);
});
// this will be the function for ajax, with the callback as parameter
function ajaxRequest(url, callback) {
$.ajax({
url: url,
method: "get",
success: function (response) {
callback(response);
},
error: function (jqXHR, exception) {
// handle errors
}
});
}
// this will be passed as callback to the ajaxRequest function
//you just need to set the innerHTML and the use animate to scroll to the bottom or to whatever height you would like
function loadcontent(message) {
$("#loadcontent").html(message);
$("#loadcontent").animate ({ scrollTop: $("#container").prop("scrollHeight") }, 10);
}
i need to do several readings HTTP, and i need wait for response. But HTTP is async. Then i don't know how.
my code is:
var clientelee = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.info("******* Recibido: " + this.responseText);
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug("****** ERROR *********"+e.error);
},
onreadystatechange: function(e){
Ti.API.info("******* STATUS *********"+e.readyState);
},
timeout : 3000 // in milliseconds
});
function LeeDatos(){
url = "http://www.hola.com/read/"+leoSerie;
// Prepare the connection.
clientelee.open("GET", url);
// Send the request.
clientelee.send();
}
for (i=0;i<NRegistros;i++){
TablaSerieTermostatos[i]=rows.field(0);
leoSerie=rows.field(0);
LeeDatos();
......
}
Any suggestion?? Thanks
On the callback could you not just pass function and when it's loaded continue with your code.
onload : function(e) {
Ti.API.info("******* Recibido: " + this.responseText);
LoadedData();
},
function LoadedData() {
// Data loaded from ASYNC Carry on...
}
or you could do it this way:
function waitForResponse( type, url, callback ) {
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.info("******* Recibido: " + this.responseText);
callback();
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug("****** ERROR *********"+e.error);
},
onreadystatechange: function(e){
Ti.API.info("******* STATUS *********"+e.readyState);
},
timeout : 3000 // in milliseconds
});
client.open(type, url);
client.send();
}
function LeeDatos(){
url = "http://www.hola.com/read/"+leoSerie;
waitForResponse( "GET", url, function() {
// Data Ready...
});
}
for (i=0;i<NRegistros;i++){
TablaSerieTermostatos[i]=rows.field(0);
leoSerie=rows.field(0);
LeeDatos();
......
}
I'm trying to set request headers of Kendo UI Editor's Upload Url and ThumbnailUrl for authorization.
$(document).on("change", "input[name=file]", function (e) {
$("#Template").data("kendoEditor").options.imageBrowser.transport.uploadUrl.beforeSend = function (xhr) {
xhr.setRequestHeader("Authorization", GetToken());
};
});
I've tried this one. Anybody knows how to set it? Kendo UI Upload have its event for upload and on the back-end Editor is also using Kendo UI Upload.
Help will be appreciated. Thanks
I got an answer from telerik support. There is no event for upload. But we can bind it in execute event. here is the code
function onExecute(e) {
if (e.name == "insertimage") {
setTimeout(function () {
var imagebrowser = $("[data-role=imagebrowser]").data("kendoImageBrowser");
imagebrowser.upload.bind("upload", function (e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
xhr.addEventListener("readystatechange", function (e) {
if (xhr.readyState === 1 /* OPENED */) {
xhr.setRequestHeader("Authorization", GetToken());
}
});
}
});
}, 0);
}
}
There isn't a way to set a header for the thumbnail request. So I've achieved this functionality by sending user id as a query string in Thumbnail request.
thumbnailUrl: hostHeaderUrl + "api/ImageBrowser/Thumbnail?userId=" + currUserId
Hopefully my answer will help.
I am using jquery file upload as below.
dialogElem.find('#upload-image-file-input').fileupload({
url: url,
dataType: 'json',
autoUpload: true,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5 MB
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true
}).on('fileuploadadd', function (e, data) {
var fileCount = data.originalFiles.length;
if (fileCount > 5) {
alert("The max number of files is : "+5);
return false;
}
}).on('fileuploadprocessalways', function (e, data) {
//some logic
}).on('fileuploadprogress', function (e, data) {
//some logic
}).on('fileuploaddone', function (e, data) {
//some logic
}).on('fileuploadfail', function (e, data) {
//some logic
})
Inside fileuploadadd I added some validation logic. If the validation is failed, how can I stop all other events like fileuploadprogress,fileuploadfail and fileuploadprocessalways ?
If u have some task like i had few weeks ago - try this:
You can cancel an in-progress upload by aborting the XHR (ajax request) call.
You can bind to the fileuploadadd event of the file input field, submit the request while keeping the jqXHR object and use it for aborting:
jqXHR.abort();
For example:
$(".cloudinary-fileupload").bind('fileuploadadd', function(e, data) {
jqXHR = data.submit(); // Catching the upload process of every file
});
$('#cancel_button').click(function (e) {
if (jqXHR) {
jqXHR.abort();
jqXHR = null;
console.log("Canceled");
}
return false;
});
The following page includes some more code samples
https://github.com/blueimp/jQuery-File-Upload/issues/290
just call
if (fileCount > 5) {
jqXHR.abort();
jqXHR = null; }
jqXHR.abort() doesnt work for me. But throw aborts "add" handling:
.bind('fileuploadadd', function (e, data) {
if (total_uploads >= maxImagesPerPost){
throw new Error('Upload maximum reached');
}