Creating Ajax based file uploaders

Tutorials

I got one interesting theme. How to upload files without refreshing whole page during submitting. Hope this will interesting to you. Lets check 2 methods – using ordinary iframes and external library. Also I will using jQuery in work too (I like it).

Here are samples and downloadable package:

Live Demo

[sociallocker]

download in package

[/sociallocker]


Ok, download the example files and lets start coding !


Step 1. HTML

As usual, we start with the HTML.

This is our main page code with both samples.

templates/main.html

01 <script src="js/jquery.min.js"></script>
02 <script src="js/ajaxupload.3.6.js"></script>
03 <script src="js/jquery.ui.widget.js"></script>
04 <script src="js/jquery.ui.accordion.js"></script>
05 <script src="js/main.js"></script>
06 <link rel="stylesheet" href="templates/css/jquery.ui.theme.css" type="text/css" />
07 <link rel="stylesheet" href="templates/css/jquery.ui.accordion.css" type="text/css" />
08 <link rel="stylesheet" href="templates/css/main.css" type="text/css" />
09 <div class="examples">
10     <div id="accordion" class="accordion">
11         <h3><a href="#">Ajax file upload into (hidden) iframe</a></h3>
12         <div class="sample_1">
13             <form id="file_upload_form" method="post" enctype="multipart/form-data" action="index.php" target="upload_target">
14                 <input name="file" id="file" size="50" type="file" />
15                 <input type="submit" name="action" value="Upload" /><br />
16                 <input type="text" name="variable" value="extra values" />
17                 <input type="hidden" name="sample" value="1" />
18             </form>
19             <button onclick="$('#upload_target').slideToggle(500)" >show iframe</button>
20             <iframe id="upload_target" name="upload_target" src=""></iframe>
21             <div style="clear:both;"></div>
22             <div id="response1">awaiting for upload</div>
23             <div style="clear:both;"></div>
24             <p>
25                 First example of ajax upload. Most easy one. Just choose any image and clock 'Upload' button to process. Also you can send visible or hidden extra information. In iframe I will draw result of work. Plus we have response behavior of upload result.
26             </p>
27         </div>
28         <h3><a href="#">Ajax file upload using ajaxupload.3.6.js library</a></h3>
29         <div class="sample_2">
30             <div id="ajxiupload2">Upload button</div>
31             <div id="response2">awaiting for upload</div>
32             <div style="clear:both;"></div>
33             <p>
34                 Another good sample. Now we will using special library - ajaxupload.3.6.js. This library from <a rel="nofollow" href="http://valums.com/ajax-upload/">here</a>. Both samples very interactive and useful. Try it!
35             </p>
36         </div>
37     </div>
38 </div>

Step 2. CSS

Here are used CSS styles.

templates/css/main.css

1 body{background:#eee;font-family:VerdanaHelveticaArialsans-serif;margin:0;padding:0}
2 .examples{background:#FFF;width:570px;font-size:80%;border:1px #000 solid;margin:3.5em auto 2em;padding:1em 2em 2em}
3 .accordion h3{margin:0}
4 .accordion form{border:1px solid;background:#E6E6E6;border-color:#C3C3C3 #8B8B8B #8B8B8B #C3C3C3;margin:.5em 0;padding:.5em}
5 .accordion form label{margin-right:1em;font-weight:700;color:#900;font-size:10px}
6 iframe#upload_target{width:500px;height:400px;border:1px solid #ddd;float:left;display:none}
7 #response1,#response2{font-size:18px;text-align:center;padding:10px;width:200px;border:1px solid #ddd;margin:10px 0}
8 #ajxiupload2{background-color:#afe;font-size:18px;text-align:center;padding:10px;width:200px;border:1px solid #ddd;margin:10px 0}

templates/css/jquery.ui.accordion.css and templates/css/jquery.ui.theme.css

This is common files – styles of jquery elements. No need to give full code of that file here. It always available as a download package

Step 3. JS

Here are necessary JS file to our project.

js/main.js

01 $(document).ready(function(){
02     $("#accordion").accordion({autoHeight: false,navigation: true});
03     // for sample 1
04     var $oResponse1 = $("#response1");
05     $("#upload_target").load(
06         function() {
07         var ret = frames['upload_target'].document.getElementsByTagName("div")[0].innerHTML;
08         var data = eval("("+ret+")"); //parse json
09             $oResponse1.text(data.html);
10         }
11     );
12     // for sample 2
13     var $oResponse2 = $("#response2");
14     var button = $('#ajxiupload2'), interval;
15     new AjaxUpload(button,{
16         action: 'index.php',
17         data : {
18             'extra_info' 'some extra info',
19             'sample' : 2,
20         },
21         name: 'image',
22         onSubmit : function(file, ext){
23             this.disable();
24         },
25         onComplete: function(file, response){
26             this.enable();
27             var data = eval("("+response+")"); //parse json
28             $oResponse2.text(data.html);
29         }
30     });
31 });

js/ajaxupload.3.6.js, js/jquery.min.js, js/jquery.ui.accordion.js and js/jquery.ui.widget.js

This is common files – jQuery library with addon and our new library. No need to give full code of that file here. It always available as a download package

Step 4. PHP

Ok, here are all used PHP file:

index.php

01 <?php
02 // set error reporting level
03 if (version_compare(phpversion(), "5.3.0"">=") == 1)
04   error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
05 else
06   error_reporting(E_ALL & ~E_NOTICE);
07 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
08     if ((int)$_POST['sample'] == 1) {
09         echo '<div>' . json_encode(array(
10             'html' => 'uploaded',
11             'code' => 1,
12         )) . '</div>';
13         echo '<pre>';
14         echo "\$_POST variables:\n";
15         print_r($_POST);
16         echo "\$_FILES variables:\n";
17         print_r($_FILES);
18         echo '</pre>';
19         exit;
20     }
21     if ((int)$_POST['sample'] == 2) {
22         echo json_encode(array(
23             'html' => 'uploaded',
24             'code' => 1,
25         ));
26         exit;
27     }
28 }
29 require_once('templates/main.html');
30 ?>

Live Demo

Conclusion

Today I told you about ajaxy upload methods. Sure that you will happy play with it. You can use this material to create own scripts into your startups. Good luck!

Rate article