Reputation: 702
I want to upload a file and send to server without refreshing page.
I have following line in my HTML file
<form id="FileUploader" enctype="multipart/form-data" >
<input type="file" name="mfile" id="mfile" style='width:100%;' onchange="uploaded()">
</form>
function uploaded()
{
alert($('form#FileUploader')[0]);
var formData=new FormData($('form#FileUploader')[0]);
//alert(formData);
$.ajax({
url: "<?php echo $_SESSION['webpage']."/upload" ?>",
type: "POST",
async: true,
dataType: "JSONP",
data : formData
})
.success (function(response){
alert(response);
})
.error (function() { alert("Error") ; }) ;
}
upload.php file
if ($_FILES["mfile"]["error"] >0 )
{
echo "Error: " ;
}
else
{
if (file_exists("upload_email_files/" . $_FILES["mfile"]["name"]))
{
echo $_POST["file"]. " already exists. ";
}
else
{
$otp= move_uploaded_file('$_FILES["mfile"]"name"]','/../upload_templates/');
}
}
It's not working .Can anybody help me on this ? It is not coming in upload.php and giving me error Illegal Invocation.
Thanks, Shirish
Upvotes: 0
Views: 15198
Reputation: 9
Try this one :)
<form id="FileUploader" enctype="multipart/form-data" >
<input type="file" name="mfile" id="mfile" style='width:100%;' onchange="uploaded()">
</form>
$(document).ready(function() {
$("#form-geninfo").submit(function(e)
{
e.preventDefault();
alert($('form#FileUploader')[0]);
var formData=new FormData($('form#FileUploader')[0]);
//alert(formData);
$.ajax({
url: "<?php echo $_SESSION['webpage']."/upload" ?>",
type: "POST",
async: true,
dataType: "JSONP",
data : formData
})
.success (function(response){
alert(response);
})
.error (function() { alert("Error") ; }) ;
}
});
Upvotes: 0
Reputation: 1145
in the case of "without refreshing page", you can use hidden iframe.
For reference,
http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/ ,
http://joekuan.wordpress.com/2009/06/12/ajax-a-simplified-version-of-file-upload-form-using-iframe/
Upvotes: 3
Reputation: 5186
Check this out I haven't tested it hope this will work http://blog.new-bamboo.co.uk/2012/01/10/ridiculously-simple-ajax-uploads-with-formdata
<form id="FileUploader" enctype="multipart/form-data" >
<input type="file" name="mfile" id="mfile" style='width:100%;' onchange="uploaded()">
</form>
function uploaded()
{
alert($('form#FileUploader')[0]);
var formData=new FormData($('form#FileUploader'));//remove [0]
//alert(formData);
$.ajax({
url: "<?php echo $_SESSION['webpage']."/upload" ?>",
type: "POST",
//async: true,//Remove this line
//dataType: "JSONP",//Remove this line
data : formData
})
.success (function(response){
alert(response);
})
.error (function() { alert("Error") ; }) ;
}
Upvotes: 1