0

I wonder if there is any simple way to get request processing percent with ajax.(not jQuery)

I tried some way to get this percent on my own.

in my php file I Set response content-length.

and then I use this code for progress percent:

function ajaxPost(url,data,callBack,progress)
{
    var postPar = data;
    //for(var f in data) postPar += f+'='+data[f]+'&';

    var xmlhttp;
    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
    else
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange=function()
    {
        var percent = 0;
        if(xmlhttp.readyState>=3) percent = Math.ceil(xmlhttp.responseText.length*100/xmlhttp.getResponseHeader('Content-length'));
        progress(percent);

        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            callBack(xmlhttp.responseText);
        }
    }

    xmlhttp.open("POST",url,true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(postPar);
}

but there is some problems:

1- I cant use this function for another site except this.(because other sites may not have content-length header)

2- this code is not working with upload requests.

Now I want to know is there any way to improve this or maybe some better way to do ?

thanks in advance...

Pooya
  • 1,508
  • 3
  • 17
  • 38
  • Browser also depend on `Content-Length` when downloading data. When you download a file without this header, the browser doesn't show a working progress bar either. – Daniel W. Aug 26 '14 at 08:53
  • I think you have to know file size: http://stackoverflow.com/questions/5178017/get-content-from-http-request-even-if-there-is-no-contentlength-header – Hamit YILDIRIM Aug 26 '14 at 09:10
  • that is a java example my friend – Pooya Aug 26 '14 at 09:37

0 Answers0