Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find out if XMLHttpRequest.send() worked

I am using XMLHttpRequest to send a file from javascript code to a django view.I need to detect,whether the file has been sent or if some error occurred.I used jquery to write the following javascript.

Ideally I would like to show the user an error message that the file was not uploaded.Is there some way to do this in javascript?

I tried to do this by returning a success/failure message from django view , putting the success/failed message as json and sending back the serialized json from the django view.For this,I made the xhr.open() non-asynchronous. I tried to print the xmlhttpRequest object's responseText .The console.log(xhr.responseText) shows

response= {"message": "success"} 

What I am wondering is,whether this is the proper way to do this.In many articles,I found the warning that

Using async=false is not recommended

So,is there any way to find out whether the file has been sent,while keeping xhr.open() asynchronous?

$(document).ready(function(){    $(document).on('change', '#fselect', function(e){             e.preventDefault();             sendFile();         }); });  function sendFile(){    var form = $('#fileform').get(0);    var formData = new FormData(form);    var file = $('#fselect').get(0).files[0];    var xhr = new XMLHttpRequest();    formData.append('myfile', file);    xhr.open('POST', 'uploadfile/', false);    xhr.send(formData);    console.log('response=',xhr.responseText); } 

My django view extracts file from form data and writes to a destination folder.

def store_uploaded_file(request):    message='failed'    to_return = {}    if  (request.method == 'POST'):                 if request.FILES.has_key('myfile'):          file = request.FILES['myfile']          with open('/uploadpath/%s' % file.name, 'wb+') as dest:             for chunk in file.chunks():                dest.write(chunk)                message="success"    to_return['message']= message    serialized = simplejson.dumps(to_return)    if store_message == "success":       return HttpResponse(serialized, mimetype="application/json")    else:       return HttpResponseServerError(serialized, mimetype="application/json") 

EDIT:

I got this working with the help of @FabrícioMatté

xhr.onreadystatechange=function(){        if (xhr.readyState==4 && xhr.status==200){           console.log('xhr.readyState=',xhr.readyState);           console.log('xhr.status=',xhr.status);           console.log('response=',xhr.responseText);            var data = $.parseJSON(xhr.responseText);           var uploadResult = data['message']           console.log('uploadResult=',uploadResult);            if (uploadResult=='failure'){              console.log('failed to upload file');              displayError('failed to upload');           }else if (uploadResult=='success'){              console.log('successfully uploaded file');           }        }     } 
like image 550
damon Avatar asked Jun 04 '12 03:06

damon


People also ask

How do I check XMLHttpRequest status?

The read-only XMLHttpRequest. status property returns the numerical HTTP status code of the XMLHttpRequest 's response. Before the request completes, the value of status is 0. Browsers also report a status of 0 in case of XMLHttpRequest errors.

What are the types of send () method used for XMLHttpRequest?

The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events.


1 Answers

Something like the following code should do the job:

    xmlhttp.onreadystatechange = function() {       if (xmlhttp.readyState === 4) {         var response = JSON.parse(xmlhttp.responseText);           if (xmlhttp.status === 200) {              console.log('successful');           } else {              console.log('failed');           }       }     } 
like image 110
Nima Avatar answered Oct 14 '22 16:10

Nima