I am using an AJAX Form to upload a profile picture on my website through ajax but the thing is that I am not able to do it. I've made a php page for that where the form is going to be posted through ajax. Have a look:
<?php
$file = $_FILES["file"];
$filename = $_FILES["file"]["name"];
$tempdir = $_FILES["file"]["tmp_name"];
$error = $_FILES["file"]["error"];
$type = $_FILES["file"]["type"];
$size = $_FILES["file"]["size"];
$maxsize = 524288;
$allowedtypes = array("image/png", "image/jpg", "image/jpeg", "image/bmp");
$errormsg = "";
if(!empty($error))
{
switch($error)
{
case '1':
$errormsg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
break;
case '2':
$errormsg = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
break;
case '3':
$errormsg = 'The uploaded file was only partially uploaded';
break;
case '4':
$errormsg = 'No file was uploaded.';
break;
case '6':
$errormsg = 'Missing a temporary folder';
break;
case '7':
$errormsg = 'Failed to write file to disk';
break;
case '8':
$errormsg = 'File upload stopped by extension';
break;
default:
$errormsg = 'No error code avaiable';
}
} elseif(empty($tmpdir) || $tmpdir == 'none') {
$errormsg = 'No file was uploaded..';
} elseif(!in_array($type, $allowedtypes) || $size > $maxsize) {
$errormsg = 'Either image type not supported or size is extending 512 KB';
} else {
$filename = $_SESSION["username"];
$filename_array = explode(".",$_POST["filename"]);
$extension = array_pop($filename_array);
$path = 'folder/' . Utilities::GetDefaultPicturePath() . $filename . "." . $extension;
$location = $path . $filename;
move_uploaded_file($tmpdir, $location);
//for security reason, we force to remove all uploaded file
@unlink($file);
}
echo $errormsg;
?>
And here's my AJAX:
<form action="admin/upload_profile_picture.php" method="post" class="hide" enctype="multipart/form-data" id="form">
<input type="file" id="file" class="hide" name="file" />
<input type="submit" name="submit" id="submit" />
</form>
And as the form is hidden the submit is called through another button:
<button class="btn btn-primary" onclick='submitForm();'>Save changes</button>
And the file box is opened through:
<button class="btn btn-primary" id="upload">Upload</button>
And the clicks of those two buttons are called through this script:
$("#upload").click(function () {
$("#file").click();
});
$("#save").click(function () {
$("#submit").click();
});
And lastly the ajaxForm() jquery plugin script is here:
$('#form').ajaxForm(function (data) {
console.log(data);
});
As you can see that I am logging the data that is returned. What I always get on submitting the form is that "No file was uploaded..". And as you can see on my PHP page, that error is only printed when temporary directory of the file is either empty of is set to "none".
So what's the problem and how can I resolve the issue.
Thanks.