Reputation:
i've looked all over stackoverflow and the general internet and i can't find a simple AJAX file uploader (Just form submission). The ones i have found aren't flexible enough and don't fit my purpose. If i could ajust this script to file uploads, that would be great:
<script type="text/javascript">
function upload(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("hint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax/link.php?q="+str,true);
xmlhttp.send();
}
In the HTML i would have
<input type='file' onblur='upload(this.value)'>
Thanks
Upvotes: 1
Views: 22553
Reputation: 1011
var data = new FormData();
data.append("image_upload",jQuery("#file_upload_input")[0].files[0]);
jQuery.ajax({
url: 'url',
type: 'POST',
data: data,
cache: false,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
console.log(data, textStatus, jqXHR);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(jqXHR, textStatus, errorThrown);
}
});
Please also check for the post_max_size ini variable, you will get it using echo phpinfo();
you have to set max file size you are going to upload. By default it is 5mb I think. and also check for the other ini variable required to increase the size of post data.
Upvotes: 0
Reputation: 21386
Here is a simple ajax file uploader
And if you don't want flash, you may use this one;
Upvotes: 7
Reputation: 4054
It's not that easy. You can't use ajax directly to upload files. Think about the security issues that would cause? What if I put "/%USER%/Desktop/CreditCardsAndPasswords.txt" in your str field? In short, you need to find and use those 'non flexible' uploaders you were talking about and will have to edit them to your needs. Either that, or write one yourself to fit your purpose.
The way most 'ajax' uploaders work is they dynamically create Html input file elements, and submit a subset of your form (just the file element) to a php script on your website, which then saves the file to whatever temp directory. Then when you submit the rest of the form, you can 'catch up' with the rest of the script and handle whatever processing is necessary with the uploaded files.
There are many Many ajax 'uploaders' out there. Just do a search and find one, I can't believe all of the ones out there aren't good enough.
Upvotes: 0