Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send file input using jquery?

Tags:

jquery

file

input

i have a form that contains 3 File inputs.i want to send it via jquery.i tried serialize function in jquery,but i realized that this function don't send file inputs!

here is my form :

<form id="submit_pics" action="#" >

     file 1 : <input name="file1" id="file1" type="file" /><br />
     file 2 : <input name="file2" id="file2" type="file" /><br />
     file 3 : <input name="file3" id="file3" type="file" /><br />

     <br />
     <div>
         <a id="submit" href="javascript:;" ><img  src="uploads/images/button1.png" /></a>
     </div>

</form>

and this is my javascript code :

<script type="text/javascript">

    $(document).ready(function(){

        $("#level3").click(function(event) {

            var str = $("#submit_pics").serialize(); 
            $.ajax({
                type: "POST",
                url: "track.php",
                data: str, 
                success: function(theResponse) {

                                        $('#req_result').html(theResponse);

                                    }

                return false;   
        });

    });

like image 264
armin etemadi Avatar asked Aug 26 '10 07:08

armin etemadi


2 Answers

After some research I found that you can do it with:

$.ajax({
    url: 'track.php',
    type: 'POST',
    data: new FormData($("#submit_pics")[0]),
    processData: false,
    contentType: false
}).

I'm Java programmer (Liferay) and in the server I use this to get the File:

UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
File File1 = uploadRequest.getFile("file1");
File File2 = uploadRequest.getFile("file2");

I supose something similar exists in php.

like image 146
Joan Avatar answered Sep 21 '22 18:09

Joan


Unfortunately you can not upload files through XMLHttpRequest. AJAX doesn’t actually post forms to the server, it sends selected data to in the form of a POST or GET request. Javascript is not capable of grabbing the file from the users machine and sending it to the server

You can use a tricky workaround, posting (without AJAX) the request to an hidden iframe.

Have a look at this TUTORIAL

like image 41
dmarucco Avatar answered Sep 21 '22 18:09

dmarucco