Output to div via jquery.ajax gradually as it loads

Question:

The task is to display the result in a div when a jquery.ajax-запросе not when it is fully received by the browser, but as it loads. It is necessary if the data is large enough. The success or complete event is not suitable because are triggered after the data is fully loaded.

Actually, the question is, is there an implementation option? Dividing data on the server into parts and pooling are not considered.

Thanks to the answers (thank you all!) I figured it out. There is a solution, based on the use of the jqXHR object. For details, follow the link http://incode.pro/jquery/ajax-na-praktike-progress-bar-indikator-protsessa-zagruzki.html . I was not interested in the progress bar, because it was impossible to calculate% loading, but data output is possible if you use the target.response property of the object returned by the installed loading handler. During loading, you just need to output the response body, which is in target.response , to the required DOM element, and in whole, not in parts !. Like this:

$('#ResultBox').html(evt.target.response)

Answer:

With the html part – everything is quite simple, although not so cloudless. For the progress bar, either a tag is used (less often), or a custom one is created from any html element you like. The first two are not very cross-browser friendly, but they provide alternative text that can be used to show the percentage of download progress, slightly corrects the situation. With the second option, you have to tinker with CSS, but this is not a problem for people in the know. We will focus on the first one, because our main goal now is to understand the mechanism in JavaScript.

So, let's create a simple form for uploading a file and after the file field, place a progress bar in which we are interested in two attributes: value – the current value and max – the maximum value. Since we will be using percentages, the values ​​will range from zero to one hundred. Accordingly, the starting value (value) must be "0", and the maximum (max) – "100":

<form action="handler.php" method="post" id="my_form" enctype="multipart/form-data">
  <p>
    <label for="my_file">Файл:</label>
    <input type="file" name="my_file" id="my_file">
    <progress id="progressbar" value="0" max="100"></progress>
  </p>
  <input type="submit" id="submit" value="Отправить">
</form>

In JS, we write the $ .ajax request code and add xhr to the parameters, in the callback function of which we can work with the XMLHttpRequest object, change or supplement its behavior, access its properties and methods, set our event handlers, etc .:

$(function(){
    var progressBar = $('#progressbar');
    $('#my_form').on('submit', function(e){
        e.preventDefault();
        var $this = $(this),
            formData = new FormData($this.get(0));
        $.ajax({
            url: $this.attr('action'),  
            type: $this.attr('method'),
            contentType: false,
            processData: false,
            data: formData,
            dataType: 'json',
            xhr: function(){
                // получаем объект XMLHttpRequest
                var xhr = $.ajaxSettings.xhr();
                // добавляем обработчик события progress (onprogress)
                xhr.upload.addEventListener('progress', function(evt){
                    // если известно количество байт
                    if(evt.lengthComputable) { 
                        // высчитываем процент загруженного
                        var percentComplete = Math.ceil(evt.loaded / evt.total * 100);
                        // устанавливаем значение в атрибут value тега <progress>
                        // и это же значение альтернативным текстом для браузеров, не поддерживающих <progress>
                        progressBar.val(percentComplete).text('Загружено ' + percentComplete + '%');
                    }
                }, false);
                return xhr;
            },
            success: function(json){
                if(json){
                    $this.after(json);
                }
            }
        });
    });
});

As for the server side, we work with the file / files there, as if you downloaded them in the usual way.

Ready! Now, in order to test it on a local machine, you need to select a larger file, otherwise the download will occur almost instantly and the progress bar, you simply will not notice. What will be in the handler in this case is not important, the main thing is that it is there. And do not forget before testing, set the value of the upload_max_filesize directive to a little more than the uploaded file. For a temporary change, the easiest way to do this is in the .htaccess file by writing the line:

php_value upload_max_filesize 1000M # вместо 1000 - своё значение

Source: http://incode.pro/jquery/ajax-na-praktike-progress-bar-indikator-protsessa-zagruzki.html

Scroll to Top