Header menu

_________________________________________________________________________________

Saturday, 15 February 2014

Multiple file upload with form submit using ajax


File upload  in ajax form is always a headache to newbie. Today i am sharing a simple tutorial to upload files in ajax. What you have to do is ,just copy two files one containing form and other receiving posted data and run them .I have tried it to keep it simple so please ignore the design.

form.php
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="http://github.com/malsup/blockui/raw/master/jquery.blockUI.js?v2.31"></script>
<script type="text/javascript" src="http://github.com/malsup/form/raw/master/jquery.form.js?v2.36"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('form').ajaxForm({
    });
    $("#add_file").on("click",function(){
        var ranNum = Math.round(Math.random()*50);
        $("#fileone").append("<div id='file"+ranNum+"'><input type='file' name='file"+ranNum+"' /><button type='button' class='rem' id='rem_file"+ranNum+"'>X</button></div>");
        p_id=ranNum;
    });
    $(document).on("click",".rem",function(){
        var id=$(this).attr('id');
        var ret = id.split("_");
        $("#"+ret[1]).remove();
    });   
});
</script>

</head>
<body>
    <h1>Ajax Form submit with multiple files</h1>
    <form id="test1" action="page.php" method="POST" enctype="multipart/form-data">
        <input type="hidden" name="MAX_FILE_SIZE" value="100000" />
         <div id="fileone">
            File:<button type="button" id="add_file">Add more files</button>
        </div>
        <div id="file0">
            <input type="file"  name="file1" />
            <button type='button' class='rem' id='rem_file0'>X</button>
        </div>
        Field: <input type="text" name="name" /><br />
        Field: <input type="text" name="action" /><br />
        Field: <input type="text" name="method" /><br />
        <input type="submit" value="Submit" />
    </form>   
</body>
</html>

***********************************************************************
page.php

<?php
if($_POST){
        echo "<pre>";
        print_r($_FILES);
        print_r($_POST);
        exit;
    }
?>