Reputation: 195
I'm trying to make a single-click avatar upload form. This is the Javascript / php mixed code:
<script type="text/javascript">
function uploadavatar(){
$('#frmuploadavatar').submit();
}
<?php
if(isset($_POST["btnuploadavatar"])){
$extension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$filename = pathinfo($_FILES["file"]["name"], PATHINFO_FILENAME);
$allowedExts = array('jpg','png');
if(!in_array($extension, $allowedExts)){
?>
$('#smlavatar').html("The uploaded file is not a jpg / png image!");
$('#smlavatar').attr("class","warning");
<?php
}else if($_FILES["file"]["size"]>2097152){
?>
$('#smlavatar').html("The uploaded file shouldn't exceed 2 megabytes!");
$('#smlavatar').attr("class","warning");
<?php
}else{
$uploadpath = "avatars/" . $filename . rand(1,1000000) . "." . $extension;
move_uploaded_file($_FILES["file"]["tmp_name"], $uploadpath);
?>
$('#imgavatar').attr("src","<?php echo $uploadpath; ?>");
$('#smlavatar').html("New avatar upload successfully!");
<?php
}
}
?>
</script>
And here's the html code for form:
<form action="register.php" method="POST" id="frmuploadavatar">
<input type="file" class="avatarupload" id="inpuploadavatar" name="avatar" onchange="uploadavatar()" />
<input type="button" id="btnuploadavatar" value="Upload New Avatar" style="width: 150px;" />
</form>
I didn't include the css code, but it's coded so that the file upload control is hidden and the button is visible but the user is actually clicking the file upload control instead of the button (file upload is on the front with z-index).
I know that the function uploadavatar() is being called by testing it with an alert. However, the form "frmuploadavatar" doesn't get submitted as the JQuery code tells it to. Help?
Upvotes: 0
Views: 1059
Reputation: 195
For single-click image upload, you need a hidden file upload and a button in a form. Make sure the form is not nested in another one.
<form action="do_upload.php" id="frmupload">
<input type="file" id="inpupload" style="display:none" />
<input type="button" id="btnupload" value="Upload Avatar" />
</form>
Then use JQuery to trigger the file upload click on the button click:
$(document.body).ready(function(){
$("#btnupload").click(function(){ $("#inpupload").trigger("click"); });
$("#inpupload").change(function(){ $("#frmupload").submit(); });
});
Done! You can also replace the inpupload's change function with ajax upload code if you wanted to.
Upvotes: 1