How To Upload Files Amongst Codeigniter Together With Ajax?

Uploading files asynchronously alongside CodeIgniter tin last confusing as well as frustrating experience. In this tutorial I volition percentage the steps how I successfully implemented a file upload alongside CodeIgniter as well as ajax.

You involve CodeIgniter, jQuery, as well as the script AjaxFileUpload which yous tin re-create from bottom of this tutorial.

It's assumed yous conduct keep a working cognition of CodeIgniter as well as jQuery. But no prior cognition of AjaxFileUpload is necessary. It is likewise assumed that yous already conduct keep successfully gear upward CodeIgniter. For the sake of brevity as well as clarity, nosotros are non going to utilisation database to relieve file information.

Step 1. Creating a form
Create your thought as well as advert it upload.php. This thought volition incorporate our upload form.

 <!doctype html> <html> <head>  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>  <script src="<?php echo base_url()?>js/custom.js"></script>  <script src="<?php echo base_url()?>js/ajaxfileupload.js"></script> </head> <body>  <h1>Upload File</h1>  <form method="post" action="" id="upload_file">  <label for="userfile">File</label>
<input type="file" name="userfile" id="userfile" size="20" /> <input type="submit" name="submit" id="submit" /> </form> <h2>Files</h2> <div id="files"></div> </body> </html>
At the top; jQuery, AjaxFileUpload, as well as our ain custom javascript files are loaded.
Then, nosotros created a criterion HTML form. The empty #files div is where the confirmation/failure message volition last displayed.
Step 2. Custom Javascript
Create custom.js within 'js' folder as well as Place the next code:
 $(function() {     $('#upload_file').submit(function(e) {         e.preventDefault();         $.ajaxFileUpload({             url             :base_url + './upload/upload_file/',              secureuri       :false,             fileElementId   :'userfile',             dataType: 'JSON',             success : business office (data)             {                var obj = jQuery.parseJSON(data);                                 if(obj['status'] == 'success')                 {                     $('#files').html(obj['msg']);                  }                 else                  {                     $('#files').html('Some failure message');                   }             }         });         supply false;     }); }); 
The JavaScript hijacks the degree submit as well as AjaxFileUpload takes over. In the background, it creates an iframe as well as submits the information via that.
We as well as thence cheque our supply (which volition last inwards JSON). Depending on the status(success/error), nosotros display message.
Step 3. Uploading a File
The Controller
The URL nosotros are uploading to is /upload/upload_file/, thence practise a novel method inwards the upload controller, as well as house the next code inwards it.
 world business office upload_file() {   $status = "";   $msg = "";   $file_element_name = 'userfile';   if ($status != "error") {   $config['upload_path'] = './uploads/';   $config['allowed_types'] = 'gif|jpg|png|doc|txt';   $config['max_size'] = 1024 * 8;   $config['encrypt_name'] = FALSE;    $this->load->library('upload', $config);   if (!$this->upload->do_upload($file_element_name))   {     $status = 'error';     $msg = $this->upload->display_errors('', '');   }   else    {    $data = $this->upload->data();    $image_path = $data['full_path'];    if(file_exists($image_path))    {       $status = "success";       $msg = "File successfully uploaded";  }  else  {   $status = "error";   $msg = "Something went incorrect when saving the file, delight endeavor again.";  } }  @unlink($_FILES[$file_element_name]);  }  echo json_encode(array('status' => $status, 'msg' => $msg)); }  
This code loads inwards the CodeIgniter upload library alongside a custom config. Remember to delete the temp file off the server, as well as echo out the JSON thence nosotros know what happened.

Files Folder
We should likewise practise the folder our files volition last uploaded to. Create novel file inwards your spider web beginning called 'uploads', making certain it is writable yesteryear the server.

That's it, tutorial complete! If yous run it, yous should last able to upload a file, come across it appear, all without leaving the page.

Note: I haven't added displaying, editing as well as deleting files.

Goodies:
Copy as well as glue the next javascript code as well as relieve every bit ajaxfileupload.js.

 jQuery.extend({    createUploadIframe: function(id, uri) { //create frame       var frameId = 'jUploadFrame' + id;       var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; if(window.ActiveXObject) {         if(typeof uri== 'boolean'){ iframeHtml += ' src="' + 'javascript:false' + '"';          }         else if(typeof uri== 'string'){ iframeHtml += ' src="' + uri + '"';          } } iframeHtml += ' />'; jQuery(iframeHtml).appendTo(document.body);        supply jQuery('#' + frameId).get(0);   },   createUploadForm: function(id, fileElementId, data) { //create degree var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var degree = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); if(data) { for(var i inwards data) { jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); } } var oldElement = jQuery('#' + fileElementId); var newElement = jQuery(oldElement).clone(); jQuery(oldElement).attr('id', fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form);  //set attributes jQuery(form).css('position', 'absolute'); jQuery(form).css('top', '-1200px'); jQuery(form).css('left', '-1200px'); jQuery(form).appendTo('body'); supply form;   },    ajaxFileUpload: function(s) {     // TODO innovate global settings, allowing the customer to alter them for all requests, non alone timeout     s = jQuery.extend({}, jQuery.ajaxSettings, s);     var id = novel Date().getTime()     var degree = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data)); var io = jQuery.createUploadIframe(id, s.secureuri); var frameId = 'jUploadFrame' + id; var formId = 'jUploadForm' + id;     // Watch for a novel laid of requests     if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); }           var requestDone = false;     // Create the asking object     var xml = {}      if ( s.global )       jQuery.event.trigger("ajaxSend", [xml, s]);     // Wait for a reply to come upward dorsum     var uploadCallback = function(isTimeout) { var io = document.getElementById(frameId);       endeavor { if(io.contentWindow) {  xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;          xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;  }else if(io.contentDocument) {  xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;         xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; }       }catch(e) { jQuery.handleError(s, xml, null, e); }       if ( xml || isTimeout == "timeout") {         requestDone = true;         var status;         endeavor {           condition = isTimeout != "timeout" ? "success" : "error";           // Make certain that the asking was successful or notmodified           if ( condition != "error" ) {             // procedure the information (runs the xml through httpData regardless of callback)             var information = jQuery.uploadHttpData( xml, s.dataType );               // If a local callback was specified, burn downward it as well as travel yesteryear it the information             if ( s.success )               s.success( data, condition );               // Fire the global callback             if( s.global )               jQuery.event.trigger( "ajaxSuccess", [xml, s] );           } else             jQuery.handleError(s, xml, status);         } catch(e) {           condition = "error";           jQuery.handleError(s, xml, status, e);         }          // The asking was completed         if( s.global )           jQuery.event.trigger( "ajaxComplete", [xml, s] );          // Handle the global AJAX counter         if ( s.global && ! --jQuery.active )           jQuery.event.trigger( "ajaxStop" );          // Process upshot         if ( s.complete )           s.complete(xml, status);          jQuery(io).unbind()          setTimeout(function() {try { jQuery(io).remove(); jQuery(form).remove();  } catch(e) { jQuery.handleError(s, xml, null, e); }  }, 100)          xml = cipher        }     }     // Timeout checker     if ( s.timeout > 0 ) {       setTimeout(function(){         // Check to come across if the asking is nevertheless happening         if( !requestDone ) uploadCallback( "timeout" );       }, s.timeout);     }     endeavor {  var degree = jQuery('#' + formId); jQuery(form).attr('action', s.url); jQuery(form).attr('method', 'POST'); jQuery(form).attr('target', frameId);       if(form.encoding) { jQuery(form).attr('encoding', 'multipart/form-data');          }       else { jQuery(form).attr('enctype', 'multipart/form-data');       }       jQuery(form).submit();      } catch(e) {       jQuery.handleError(s, xml, null, e);     }  jQuery('#' + frameId).load(uploadCallback);     supply {abort: business office () {}};    },    uploadHttpData: function( r, type ) {     var information = !type;     information = type == "xml" || information ? r.responseXML : r.responseText;     // If the type is "script", eval it inwards global context     if ( type == "script" )       jQuery.globalEval( information );     // Get the JavaScript object, if JSON is used.     if ( type == "json" )       eval( "data = " + information );     // evaluate scripts within html     if ( type == "html" )       jQuery("<div>").html(data).evalScripts();      supply data;   } })   
If yous are looking for delete as well as display features, yous tin uncovering inwards below tutorial.

Reference site: http://code.tutsplus.com/tutorials/how-to-upload-files-with-codeigniter-and-ajax--net-21684


Sumber http://developer-paradize.blogspot.com

Comments

Popular posts from this blog

What Are The Main Components of a Computer System

Top Qualities To Look For In An IT Support Team

How To Integrate Google Adwords Api Into Codeigniter?