JSFiddle - React, Tailwind, and code Playground
by Benahmed Taoufiq
HTML
<form id="maform" method="post" enctype="multipart/form-data">
<input type="text" id="text" name="text" value="test" />
<input type="file" id="fichier" name='fichier[]' />
</form>
<input type="button" id="Sub" value="envoyer"/>
<div id="result">
</div>
<a id="progress">
</a>
CSS
#progress{
text-align:center;
color:white;
width:100%;
background-color:black;
}
JavaScript
$(function(){
var result=$("#result");
$("#Sub").click(function(){
$("#progress").css("width",0);
var data={
json :{text:$('#text').val(),fichier:$("#fichier")[0].files[0]}
//json: $('#maform').serializeArray()
};
var formdata = window.FormData? new FormData():alert("navigateur ne supporte pas formdata");
formdata.append("json",data.json.fichier);
formdata.append("json",JSON.stringify(data.json.text));
$.ajax({
type: "POST",
xhr: function() { // Custom XMLHttpRequest
var myXhr = new XMLHttpRequest();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
url:"/echo/json/",
data:formdata,
dataType: "json",
cache: false,
contentType: false,
processData: false,
success:function(rep){
console.log(formdata);
$.each(data, function(i, field){
result.html("");
$.each(field,function(key,val){
result.append(key+": "+val+" ");
});
});
}//fin success
});//fin ajax
}); //fin click
});
function progressHandlingFunction(e){
if(e.lengthComputable){
console.log("loaded :"+e.loaded+" total :"+e.total);
$('#progress').text("chargement...")
.animate({
"background-color":+(e.loaded/e.total)*100+"%",
"width":+(e.loaded/e.total)*100+"%"
});
if(e.loaded==e.total)
{
$('#progress').text("Upload Terminée.");
}
}
}