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?