Reputation: 403
I have a web page which has an upload box and uploads an image. the jquery is as follows. User browses a file and clicks a button named btn_AddImage and the file is uploaded. The problem is that the code only works when I put breakpoint on "if (xhr.readyState == 4)" in firebug and the "btn_ShowImage" element is shown. If i do not put the break point, the file would be uploaded but the page still alerts error and the "btn_ShowImage" element would be still hidden.
$(document).ready(function () {
$('#btn_AddImage').live('click', AjaxFileUpload);
});
function AjaxFileUpload() {
var fileInput = document.getElementById("image_Upload");
var file = fileInput.files[0];
var fd = new FormData();
fd.append("files", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'ImageFileUploader.ashx');
xhr.send(fd);
if (xhr.readyState == 4) {
$('#btn_ShowImage').show();
}
else {
alert('error');
}
}
thanks for your responses. I have corrected my code and it is working. The corrected code is as below
$(document).ready(function () {
$('#btn_AddImage').live('click', AjaxFileUpload);
});
function AjaxFileUpload() {
var fileInput = document.getElementById("image_Upload");
var file = fileInput.files[0];
var fd = new FormData();
fd.append("files", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'ImageFileUploader.ashx');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
$('#btn_ShowImage').show();
}
else if (uploadResult == 'success')
alert('error');
};
xhr.send(fd);
}
Upvotes: 0
Views: 135
Reputation: 308
The "A" in "AJAX" stands for "asynchronous" :)
Meaning: You're setting up the XHR object and inspecting its "readyState" property synchronously - even before the ajax call really went out. You should rather set up and fire the AJAX request and listen for the "readyStateChange" event - this might get called multiple times until the request is fully completed.
Another question that comes to mind immediately: You're using jQuery for event binding on the button - why do you fiddle around with XHR yourself and not simply also use jQuery for AJAX?
Upvotes: 3