On the submit() event of the form, I'm trying to send the serialzedData to my PHP code for uploading the file using AJAX(both of which I'm new to). The PHP Code for uploading the file normally works if used directly without AJAX. I'm guessing its the AJAX portion that is not working...Any ideas?
Form(index.php)
<form id="upload-file" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit" id="upload_button">
</form>
JQUERY/AJAX(index.js)
$(document).ready(function(){
var request;
$("#upload-file").submit(function(){
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "fileupload.php",
type: "post",
data: serializedData
});
request.done(function (response, textStatus, jqXHR){
console.log("Hooray, it worked!");
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrow
);
});
request.always(function () {
$inputs.prop("disabled", false);
});
event.preventDefault();
});
});
PHP(fileupload.php)
<?php
$fileToUpload = $_POST['serializedData'];
if ($_FILES["fileToUpload"]["error"] > 0){
echo("Error");
}
else{
if (file_exists("upload/" . $_FILES["fileToUpload"]["name"])){
echo("File Exists");
}
else{
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"upload/" . $_FILES["fileToUpload"]["name"]);
echo("File Uploaded");
}
}
?>
And the directory structure is
-index.php
-js(folder)
-index.js
-fileupload.php
-upload(folder)