I wish to upload an image to the server via ajax using jQuery and FormData.
My jQuery code is as follows
var formData = new FormData("form")[0];
var fileName = $("#InputLogo")[0].files[0].name;
$.ajax ( {
url : 'upload.php',
type : 'POST',
data : { "data" : formData, "fileName" : fileName },
processData : false,
success : function(data) {
console.log(data);
alert(data);
}
});
This code is called when the user selects a new file to upload.
MY server backend is PHP and it handles the request as follows
$data = $_POST['data'];
$fileName = $_POST['fileName'];
$fp = fopen('/img/'.$fileName, 'w');
fwrite($fp, $data);
fclose($fp);
$returnData = array("data" => $data);
print_r($_POST);
The POST request does occur, but $_POST remains empty.
I tried searching for the solution but couldn't find an exact one.
Any suggestions would be appreciated.
EDIT : Here is the form in HTML
<form id=card-form" method="post" action="" >
<div class="form-group">
<label for="InputName">Name of the Company</label>
<input type="text" class="form-control" id="InputName" placeholder="Enter a name">
</div>
<div class="form-group">
<label for="InputEmail">Email</label>
<input type="email" class="form-control" id="InputEmail" placeholder="Enter email">
</div>
<div class="form-group">
<label for="InputLogo">Choose a company logo</label>
<input type="file" id="InputLogo" accept="image/*">
<p class="help-block">For good visibility, please limit the image to 200 x 200 px</p>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>