Possible Duplicate:
Ajax file upload
Is it possible to write an ajax request with JQuery that "submits" a form with a file field? I want to do it because in this way i can make the user upload a file without leaving the current page.
How should i write the $.ajax() call? and in particular how should i set into the ajax call the file field?
EDIT: I'd like to use only core JQuery functions, without plugins.
Thanks.
To maintain compatibility with the widest range of browsers this needs to be done through a hidden iframe.
Here is some sample code to demonstrate what I mean:
<iframe name="my_iframe" id="my_iframe" style="display: none;"></iframe>
<form action="/next_step.php" method="post" target="my_iframe" entype="multipart/form-data">
<input type="file" name="file_upload" />
<input type="button" id="upload_btn" value="Upload file" />
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<input type="submit" value="Next step" />
</form>
<script type="text/javascript">
var btn = document.getElementById('upload_btn');
btn.onclick = function(){
var form_elem = document.forms[0];
// direct file uploads through the hidden iframe
form_elem.action = '/test_file.php';
form_elem.target = 'my_iframe';
// submit the form
form_elem.submit();
};
</script>
There are projects out there that make this easier such as Plupload
It's hard. You're much better to use a service that already exists.
I did this recently on a site because I needed the whole form to submit without reloading the page, and uploadify was the best AJAX file uploader I found.