I want to pass a file from a file input form to a php script via ajax and process the message my php script echoes.
This is my html form:
<form id="fileUploadForm" method="POST" enctype="multipart/form-data">
<input name="fileToUpload" id="fileToUpload" type="file">
<button type="submit" name="submit" id="submit">Upload</button>
</form>
my js code:
$('#submit').click(function() {
var file_data = $('#fileToUpload').prop('files')[0];
var form_data = new FormData();
form_data.append('fileToUpload', file_data);
$.ajax({
url: 'form.php',
dataType: 'text',
data: form_data,
processData: false,
contentType: false,
type: 'post',
success: function(data) {
alert(data);
},
});
and my (simplified) php script:
<?php
//some code
if(fileTooLarge){
echo "Your file is too large!";
}
if(success){
echo "Your file has been uploaded";
}
?>
What I want to achieve is the the user gets a message if the file was uploaded successfully or it was too big/ had wrong extension without reloading the page.