PHP Ajax Parameter on Upload not set?
Ad
I try to do a simple simple upload but i guess iam too dumb or its too late here.
I searched a bit and founded this here on Stack
HTML
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File to stash:</label>
<input type="file" name="file" required />
</form>
<input id="uploadBTN" type="button" value="Stash the file!"></input>
<div id="output"></div>
JS
$("#uploadBTN").click(function(event) {
var fd = new FormData($("#fileinfo"));
//fd.append("CustomField", "This is some extra data");
$.ajax({
url: './ajax/upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
PHP
if(isset($_POST['file'])){
$filename = $_FILES['file']['name'];
if(isset($filename) && !empty($filename)){
echo 'sup my man?!';
}else{
echo 'please choose a file';
}
}else{
echo 'not set';
}
The Problem with these Stuff is its saying not set so? With GET Method its same cause i tested mostly everthing out. And no i dont want to use any plugin or something else :)
My Question is how can i access correctly the File ? Or if this Lines of Code are totally Crap what is a other solve?
Thanks!
Ad
Answer
Ad
Try this, It works for me.
$("#uploadBTN").click(function(event) {
event.preventDefault();
var tmp_form = $("#fileinfo")[0];
var fd = new FormData(tmp_form);
$.ajax({
url: './ajax/upload.php',
type: 'POST',
data: fd,
async: true,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
<form action="" method="post" enctype="multipart/form-data" id="fileinfo">
<input type="file" name="file" required >
</form>
<input id="uploadBTN" type="button" value="Stash the file!"></input>
<div id="output"></div>
if(isset($_FILES['file'])){
$filename = $_FILES['file']['name'];
if(isset($_FILES['file']['name']) && !empty($filename)){
echo 'sup my man?!';
}else{
echo 'please choose a file';
}
}else{
echo 'not set';
}
Ad
source: stackoverflow.com
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad