onReadyStateChange not firing in IE for XHR Request - javascript

I have this code that I am using and it works fine in chrome, but in IE, it looks like that onreadystatechenge is not firing.
How do I get this to work cross browser. I read that in IE you have to place the onreadystatechange event before the send, But that didn't work.
The alert here is not firing. And yes it is successful.
if (xhr.status==200 && xhr.readyState==4)
{
alert("DONE!");
}
This is the entire request.
function SendFile(evt)
{
var xhr = new XMLHttpRequest();
var data = new FormData();
var files = $("#FileUpload1").get(0).files;
for (var i = 0; i < files.length; i++)
{
data.append(files[i].name, files[i]);
}
xhr.upload.addEventListener("progress", function (evt)
{
if (evt.lengthComputable)
{
var progress = Math.round(evt.loaded * 100 / evt.total);
$("#progressbar").progressbar("value", progress);
}
}, false);
xhr.open("POST", "Handler.ashx");
xhr.onreadystatechange=function ()
{
if (xhr.status==200 && xhr.readyState==4)
{
alert("DONE!");
}
}
xhr.send(data);
$("#progressbar").progressbar({
max: 100,
change: function (evt, ui)
{
$("#progresslabel").text($("#progressbar").progressbar("value") + "%");
},
complete: function (evt, ui)
{
$("#progresslabel").text("File upload successful!");
GetID();
}
});
}
Tried onload with no luck.
xhr.onload = function ()
{
if (xhr.readyState == 4 && xhr.status==200)
{
alert("IE DONE!");
}
}

Your XMLHttpRequest object might be caching.
Try:
var myNoCachePage = document.location + '?' + new Date().getTime();
xhr.open("GET", myNoCachePage, true); // Prevent IE11 from caching
xhr.send();

Apparently IE 11 (which I assume is what you are testing is broken) removed script.onreadystatechange in favor of script.onload.
Here is the compatibility for xhr.onload.
Source of IE11 removing it

Related

Upload file by XMLHttpRequest does not work with Microsoft Edge, but others

This java-script code works well with other browsers except Microsoft Edge, After the send(file) method is called, the request is not sent.
this.uploadFile = function (file, index, filesStorage) {
try {
if (file == undefined || file == null) { return; }
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.hasLoaded = false;
// Update progress bar
xhr.upload.addEventListener("loadstart", function (event) { filesManager_5.startFileProgress(event, file.uid); }, false);
xhr.upload.addEventListener("progress", function (event) { filesManager_5.updateFileProgress(event, file.uid); }, false);
xhr.upload.addEventListener("loadend", function (event) { filesManager_5.endFileProgress(event, file.uid); }, false);
xhr.addEventListener("readystatechange", function (event) { filesManager_5.changeStateFileProgress(event, file.uid, this.readyState); }, false);
xhr.upload.addEventListener("error", function (event) { alert('Error!'); }, false);
//xhr.upload.addEventListener("abort", function (event) { alert('Abort!'); }, false);
xhr.open("post", "~/Html5UploadHandler.ashx", true);
xhr.setRequestHeader("Content-Type", file.type);
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('X-Upload-Id', GetUploadId());
this._fileRequests[file.uid] = xhr;
xhr.send(file);
} catch (e) {
alert(e);
}
};
It works after I change to this
var reader = new FileReader();
reader.onload = function(){
var arrayBuffer = this.result;
xhr.send(arrayBuffer);
}
reader.readAsArrayBuffer(file);

Web Workers and JSON

I am sure there is something that I am missing from this code, I just can not figure out what it is.
Here is the main page:
<script>
function wwCallback(e) {
document.write(e.data);
}
function wwError(e) {
alert(e.data)
}
$(document).ready(function () {
var worker = new Worker("sync.js");
worker.onmessage = wwCallback;
worker.onerror = wwError;
worker.postMessage({
'cmd': 'downloadUser',
'url': 'server.php'
});
console.log("WW Started");
});
</script>
Server.php simply echoes a JSON string and I have verified that it is both valid and working using normal ajax requests.
Here is my web workers code:
function getData(url) {
var req = new XMLHttpRequest();
//expect json
req.open('GET', url);
req.send(null);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
self.postMessage(req.responseText);
}
}
}
}
self.addEventListener('message', function (e) {
var data = e.data;
switch (data.cmd) {
case 'downloadUser':
getData(data.url);
}
self.close();
}, false);
Could anyone point me in the right direction?
Your problem is in your WebWorker XHR call. You've opened the request, then immediately sent it before you've set up the event handler to handle the response. You just need to move the req.send(null); call below the code that sets up the event handler.
Try this:
function getData(url) {
var req = new XMLHttpRequest();
//expect json
req.open('GET', url);
// req.send(null); // remove this line from here.
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
self.postMessage(req.responseText);
}
}
}
req.send(null); // make the request after your readystatechange
// handler is set up.
}
self.addEventListener('message', function (e) {
var data = e.data;
switch (data.cmd) {
case 'downloadUser':
getData(data.url);
}
self.close();
}, false);

PUT/DELETE XMLHttpRequest Not Working in Firefox

I am working with javascript cross domain ajax request. my code is working fine on chrome and other devices like android browser and android native app using phonegap.
But i was facing issue with Firefox..
Firefox does not support my PUT and DELETE requests.
Is there any solution for firefox to make put and delete request to my server.
firefox does support my post and get request. both request working fine.
here is my working code.
var XMLHttpFactories = [
function () {
return new XMLHttpRequest()
},
function () {
return new ActiveXObject("Msxml2.XMLHTTP")
},
function () {
return new ActiveXObject("Msxml3.XMLHTTP")
},
function () {
return new ActiveXObject("Microsoft.XMLHTTP")
}
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}
For send Put request..
var xhr = createXMLHTTPObject();
xhr.open("PUT", url,true);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4)
{
if(xhr.status==200){
request.success(xhr.responseText);
}else if(xhr.status!=200){
request.error(xhr.responseText)
}
}
}
xhr.send(body);
The following is working just fine on Firefox 22.0 (& 23.0 too):
var XMLHttpFactories = [
function () {
return new XMLHttpRequest()
},
function () {
return new ActiveXObject("Msxml2.XMLHTTP")
},
function () {
return new ActiveXObject("Msxml3.XMLHTTP")
},
function () {
return new ActiveXObject("Microsoft.XMLHTTP")
}
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}
var xhr = createXMLHTTPObject();
xhr.open("PUT", "/echo/html/", true);
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
alert("Request completed, with the following status code: " + xhr.status);
}
xhr.send("");
Here is a jsFiddle: http://jsfiddle.net/qXQtD/
To better understand your situation, please answer the following:
What is the data you are trying to send?
What are your complete response headers (especially the "Access-Control-Allow-Origin" header)?

Why might XMLHttpRequest ProgressEvent.lengthComputable be false?

I'm trying to implement a upload progress bar the HTML5 way, by using the XMLHttpRequest level 2 support for progress events.
In every example you see, the method is to add an event listener to the progress event like so:
req.addEventListener("progress", function(event) {
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded * 100 / event.total);
console.log(percentComplete);
}
}, false);
Such examples always seem to assume that event.lengthComputable will be true. After all, the browser knows the length of the request it's sending, surely?
No matter what I do, event.lengthComputable is false. I've tested this in Safari 5.1.7 and Firefox 12, both on OSX.
My site is built using Django, and I get the same problem on my dev and production setups.
The full code I'm using to generate the form upload is shown below (using jQuery):
form.submit(function() {
// Compile the data.
var data = form.serializeArray();
data.splice(0, 0, {
name: "file",
value: form.find("#id_file").get(0).files[0]
});
// Create the form data.
var fd = new FormData();
$.each(data, function(_, item) {
fd.append(item.name, item.value);
});
// Submit the data.
var req = new XMLHttpRequest();
req.addEventListener("progress", function(event) {
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded * 100 / event.total);
console.log(percentComplete);
}
}, false);
req.addEventListener("load", function(event) {
if (req.status == 200) {
var data = $.parseJSON(event.target.responseText);
if (data.success) {
console.log("It worked!")
} else {
console.log("It failed!")
}
} else {
console.log("It went really wrong!")
}
}, false);
req.addEventListener("error", function() {
console.log("It went really really wrong!")
}, false);
req.open("POST", "/my-bar/media/add/");
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
req.send(fd);
// Don't really submit!
return false;
});
I've been tearing my hair out for hours on this. Any help appreciated!
Hey I found the answer from #ComFreek:
I made the same mistake.
The line I wrote was:
xhr.onprogress = uploadProgress;
The correct one should be
xhr.upload.onprogress = uploadProgress;
take a look into this :
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
xhr.upload.addEventListener('progress',function(e){}) will also work.
I also had problem with sending multiple big files using AJAX (xmlhttprequest).
Found a solution and here is whole script that I use.
All you need is to place next line in your HTML page:
<input type="file" multiple name="file" id="upload_file" onchange="handleFiles(this)">
and use next script:
<script type="text/javacript">
var filesArray;
function sendFile(file)
{
var uri = "<URL TO PHP FILE>";
var xhr = new XMLHttpRequest();
var fd = new FormData();
var self = this;
xhr.upload.onprogress = updateProgress;
xhr.addEventListener("load", transferComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
function updateProgress (oEvent)
{
if (oEvent.lengthComputable)
{
var percentComplete = oEvent.loaded / oEvent.total;
console.log(Math.round(percentComplete*100) + "%");
} else {
// Unable to compute progress information since the total size is unknown
console.log("Total size is unknown...");
}
}
function transferComplete(evt)
{
alert("The transfer is complete.");
}
function transferFailed(evt)
{
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt)
{
alert("The transfer has been canceled by the user.");
}
function handleFiles(element)
{
filesArray = element.files;
if (filesArray.length > 0)
{
for (var i=0; i<filesArray.length; i++)
{
sendFile(filesArray[i]);
}
filesArray = '';
}
}
</script>
Your result will be in console

Dynatree IE9 problems loading

I´ve implemented a dynatree on a web application, dynatree is generated from server with a JSON object.
Dynatree works perfectly on Firefox, Safari, Chrome and Opera (last versions), but when I open on IE9, I just capable of loading the tree after refresh the page, or start the debug mode. I can´t find any mistake on console, script....
Any suggestion? someone with the same problem?
Code:
function hacerPeticion(url, callback){
var request;
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function(){
if (request.readyState == 4 && request.status == 200){
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
Using the function:
hacerPeticion('/ServiciosWeb/Zonas.jsp', function(data){
var data = JSON.parse(data.responseText);
var arbol = data;
eval('var obj='+arbol);
console.log(obj);
$(function(){
$("#tree3").dynatree({
checkbox: true,
selectMode: 3,
children: obj,
onSelect: function(select, node) {
if(!select){
if(node.data.key=="zonas"){
control=false;
cargaMapaCYL(map, control);
}
if(node.data.key=="ast"){
control=false;
cargaMapaAst(map, control);
}
/*Nodos seleccionados*/
if(select){
if(node.data.key=="zonas"){
control=true;
cargaMapaCYL(map, control);
}
if(node.data.key=="ast"){
control=true;
cargaMapaAst(map, control);
}
}
onDblClick: function(node, event){
node.toggleSelect();
},
onKeydown: function(node, event) {
if( event.which == 32 ) {
node.toggleSelect();
return false;
}
}
});
Thanks in advance.
So....., the problem is in this line:
console.log(obj);
When I have retired this line everything works fine.

Categories

Resources