Enviando dados e realizando upload de arquivos via AJAX
Em alguns momento temos a necessidade de enviar os dados de nossos formularios via AJAX.
Abaixo segue um exemplo de upload de arquivo em ajax utilizando uma grande biblioteca feita pelo MICO, micoxUpload.
1º - Arquivo Principal
Incluimos a biblioteca
1 2 | <script language="javascript" type="text/javascript" src="micoxUpload2.js"></script> |
Escrevemos as funcoes auxliares
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <script>
function end_upload(data){
document.getElementById('retornoForm').innerHTML = data; //Informo a div de retorno
}
function enviaDados(frm) {
micoxUpload2(frm, 'salva.php', 50, 'Carregando...', end_upload); //informo o arquivo de envio
}
</script>
Chamo a funcao responsavel por indexar os dados no envento onSubmit do meu formulario
<pre lang='html' line='1'>
<form name="frm2" id="frm2" method="post" enctype="multipart/form-data" onsubmit="enviaDados('frm2'); return false;" >
<input name="foto" type="file" class="campos" id="foto" size="37" />
<input type='submit' value='envia' >
</form>
<div id='retornoForm'></div> <!-- ESTA È MINHA DIV DE RETORNO--> |
2º - Arquivo salva.php
No arquivo salva.php apenas realizo o upload do arquivo e mostro o mesmo no browser.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php if(!empty($_FILES['foto']['name'])){ //Se existir arquivo para Upload eu faço o mesmo $ext =explode(".", $_FILES['foto']['name']); $nome= mktime().mt_rand(1,100).".".$ext[1]; //Pego a extenção do arquivo move_uploaded_file($_FILES['foto']['tmp_name'],$nome); }else{ $nome= null; } echo"<img src='$nome' >"; ?> |
3º - Arquivo micoxUpload2.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | function micoxUpload2(form, naction, timeout,loading,callback){ /** * micoxUpload2 - Submete um form para um iframe oculto e pega o resultado. Consequentemente pode * ser usado pra fazer upload de arquivos de forma assÃncrona. * Versão: 2.0 - 02/01/2008 * Autor: Micox - www.elmicox.com - elmicox.blogspot.com * Licença: Creative Commons - http://creativecommons.org/licenses/by/2.5/br/ * Some Rights Reserved - http://creativecommons.org/licenses/by/2.5/ **/ var $gE, addEvent, removeEvent, periodic, loadAnim, loaded, abortFrame; //small functions var error_prog = []; //errors by programer var new_form, loading_msg, loadpos=0; //the new form that will replace old form AND loading msg var z, old_action, concat, timeload, timecounter=0, iframe, name; var loads = [' ','. ','.. ','...']; //loading animation /*** small functions */ $gE = function(quem){ return document.getElementById(quem) } addEvent = function(obj, evType, fn){ if (obj.addEventListener){ obj.addEventListener(evType, fn, true) ; } if (obj.attachEvent) { obj.attachEvent("on"+evType, fn);} } removeEvent = function( obj, type, fn ) { if ( obj.detachEvent ) { obj.detachEvent( 'on'+type, fn ); } if ( obj.removeEventListener ) { obj.removeEventListener( type, fn, false ); } } loadAnim = function(){ //get animation of array loads if(loading.indexOf('<img')<0){ // 3 dots just if no image if(loadpos>loads.length - 1){ loadpos = 0; } return loads[loadpos++] + ' '; }else{ return '';} } periodic = function(){ timecounter++ ; if(timecounter/2 > timeout && timeout > 0){ //timeout expired (timeout = 0 is infinite) clearInterval(timeload); //fim do contador abortFrame(name); loaded('timeout'); } loading_msg.innerHTML = loading + ' ' + loadAnim(); } abortFrame = function(o_frame){ //stop iframe var o_frame = typeof(o_frame)=="string" ? $gE(o_frame):o_frame; if(!o_frame){ return false; } try{ o_frame.contentWindow.stop(); //FF e OP }catch(e){ try{ o_frame.contentWindow.document.execCommand('stop');//IE } catch(e){ o_frame.src = ''; /* tenta parar mermo */ } } } cloneEvents = function(source2,target,recursive){ for(var p in source2){ //all params try{if(source2[p].constructor==Function){ target[p] = source2[p] }}catch(e){} } if(recursive){ for(var el=0; el<source2.childNodes.length; el++){ var elem = source2.childNodes[el] var elem_target = target.childNodes[el] if(elem.nodeType==1){ cloneEvents(elem,elem_target); } } } } //testing callback if(typeof(callback)!='function'){ error_prog.push("The 'callback' parameter must be a function") } //testing if 'form' is a html object or a id string form = typeof(form)=="string" ? $gE(form):form; if(form.nodeName.toUpperCase()!='FORM'){ error_prog.push("The first parameter must be a form element ID or a form element reference") } //testing if form have some input file /*var input_file = false; var infile = form.getElementsByTagName('input') for(z in infile){ if(infile[z].type=='file'){ if(infile[z].value==''){ alert("The input is empty. I cant upload this.") return true; }else{ input_file = infile[z]; } } } if(input_file==false){ error_prog.push("The form must be a input type file") } */ //exit if programmer errors if(error_prog.length>0) { alert("Error in parameters of micoxUpload:\n\n" + error_prog.join('\n')); /* uncoment this if you want use try-catch-throw throw(error_prog.join('\n')) */ return true; } //random id for multiple calls rand = (m=Math).round( 20 * m.random() ); //adding callback function to global scope //window['micoxCallbackTemp' + rand] = callback //creating the iframe name = "micox-temp" + rand; iframe = document.createElement("iframe"); iframe.setAttribute("id",name); iframe.setAttribute("name",name); iframe.setAttribute("width","0"); iframe.setAttribute("height","0"); iframe.setAttribute("border","0"); iframe.setAttribute("style","width: 0; height: 0; border: none;"); //add to document form.parentNode.appendChild(iframe); window.frames[name].name = name; //ie sucks //event after load loaded = function(){ //var iframe2 = $gE(name); clearInterval(timeload); //fim do contador //first, removing the event of iframe removeEvent(iframe,'load',loaded) //removind loading msg loading_msg.parentNode.removeChild(loading_msg); //removing old form //form.parentNode.removeChild(form); //calling callback with the return if(arguments[0]!='timeout'){ callback(iframe.contentWindow.document.body.innerHTML); }else{ callback('Timeout expired. ' + timeout + ' secs.'); } //removing old iframe abortFrame(iframe); iframe.src=''; //to stop 'loadind' in FF. bug. iframe.parentNode.removeChild(iframe); delete iframe; } //adding the event addEvent(iframe,'load',loaded) //properties of form to a normal upload form.setAttribute("target",name); form.setAttribute("method","post"); form.setAttribute("enctype","multipart/form-data"); form.setAttribute("encoding","multipart/form-data"); //aditional information if micoxUpload old_action = naction; if(naction.indexOf('?')>1){ concat = '&' } else { concat = '?' } form.setAttribute("action",naction + concat + 'micoxUpload=1'); //submit form.submit(); //make loading loading_msg = document.createElement('div'); loading_msg.innerHTML = loading; form.parentNode.insertBefore(loading_msg,form); //making new form and hidden old form input_file.value=''; form.reset(); new_form = form.cloneNode(true); cloneEvents(form,new_form,true); new_form.reset(); new_naction = old_action; form.style.display = 'none'; form.parentNode.insertBefore(new_form,form); //if you want new input file before the 'loading div', use this above (invert the comment) //form.parentNode.insertBefore(new_form,loading_msg); timeload = setInterval(periodic,500); //no submit default return false; } |
Bem Acredito que seria isso, qualquer duvida, ou sugestão é so reportar no BLOG.
Até a proxima.
5 Responses to “Enviando dados e realizando upload de arquivos via AJAX”
Seu Comentário


Michel de Witte on outubro 19th, 2009
So uma pergunta!
Tem como enviar mais de um arquivo ao mesmo tempo, tipo 5 files no maximo.
Att
jadson alves on outubro 21st, 2009
Muito interessante, como seria com ASP no lugar de PHP?
Jadson Alves
admin on outubro 23rd, 2009
claro, ae terá que incluir alguns outros campos do tipo file utilizando js !
admin on outubro 23rd, 2009
Boa pergunta, não porgramo em ASP ;)
douglas on julho 1st, 2010
Eu estou tentando criar um formulario para cadastrar igrejas para um evento que vai ter, mas não consigo de forma alguma enviar os dados do formulario para o meu e-mail já olhei tudo na net e nada se tever como vc me ajudar ficaria grato