Simple jQuery AJAX file upload

I downloaded jQuery completely and got desperate to get it to work.

This is the html:

<form method="post" enctype="multipart/form-data">
    <input id="pic "type="file" name="file" onchange="javascript:this.form.submit();">
</form>

      

JQuery

$("#pic").change(function() {
    var file_data = $('#pic').prop('files')[0];
    var form_data = new FormData();
    form_data.append('file', file_data)
    alert(form_data);
    $.ajax({
                url: 'doupload.php',
                dataType: 'text',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,
                type: 'post',
                success: function(dat){
                    alert('it works maybe');
                }
     });
});

      

So I just want to send the file to doupload.php and catch it there ( $_FILES['file']['tmp_name']

)

But it doesn't work (ofc) and I don't find anything that works either google or stack ...

I am using this lilbary: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>

+3


source to share


1 answer


<input id="pic "type="file" name="file" onchange="javascript:this.form.submit();">

      

You have type = "file"

Change it to type = "file"



Also, if you have an ajax post on change through "$("#pic").change(function() {

, you MUST NOT have onchange="javascript:this.form.submit();"

, as it will submit the form while the ajax is still submitting, causing possible timing issues (e.g. ajax call does not complete)

As far as I can tell, you shouldn't have a dispatch event at all since the data has already been sent via the ajax call.

+1


source







All Articles