Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX upload progress for large text fields

Is it possible to get the upload-progress for a form with very large textfields using jQuery ajax? I think the client knows how much bytes have been sent, but when I Google I only find solutions for file-uploads using server-site code.

This is my ajax-request:

$.ajax({
        type: "POST",
        url: "index.php?action=saveNewPost",
        data: {textbox1: textbox1,textbox2: textbox2},
        contentType: "application/x-www-form-urlencoded;charset=UTF-8",
        success: function(){
            //
        }
    });

I was hoping there would be something like "onProgress" with a parameter containing the amount of bytes already sent...

Found a solution

$.ajax({
        xhr: function() {
            var req = $.ajaxSettings.xhr();
            if (req) {
                req.upload.addEventListener('progress', function(event) {
                    if (event.lengthComputable) {
                        $('#ajaxFeedbackDiv').html(event.loaded); // = 'test'; //event.loaded + ' / ' + event.total;
                    }
                }, false);
            }
            return req;
        },
        type: "POST",
        url: "index.php?action=saveNewPost",
        data: {textbox1: textbox1,textbox2: textbox2},
        contentType: "application/x-www-form-urlencoded;charset=UTF-8"
        }
    });

this seems to work, altough there are still

2 problems:

  1. the connection on my localhost is way too fast, so it's hard to see the "progress" actually working. I installed this tool http://mschrag.github.com on a second Mac in the same network and I see that it's working perfectly.
  2. I'm not sure if this will fall-back friendly on non-XHR/HTML5-compatible browsers, i.e. just upload without progress information?
like image 962
Raphael Jeger Avatar asked Oct 04 '22 13:10

Raphael Jeger


1 Answers

You could achieve this with the new XMLHttpRequest object in HTML5 capable browsers. It supports the progress event that you could subscribe to and be notified of the AJAX operation.

Here's an example:

document.getElementById('myForm').onsubmit = function() {
    var xhr = new XMLHttpRequest();

    xhr.upload.addEventListener('progress', function(e) {
        if (e.lengthComputable) {
            var percentage = Math.round((e.loaded * 100) / e.total);
            document.getElementById('progress').innerHTML = percentage + '%';
        }
    }, false);

    xhr.open(this.method, this.action, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    };

    xhr.send(new FormData(this));
    return false;    
};

and here's a live demo.

like image 90
Darin Dimitrov Avatar answered Oct 10 '22 00:10

Darin Dimitrov