I am new to ajax (and try to avoid frameworks), I tried to check through PHP if any file is set and show true
or false
, but it didn't worked so I wonder what I did wrong.
This is my code, HTML and JS:
<form class="file-upload" enctype="multipart/form-data" method="post" action="post.php">
<input type="file" name="fu-obj" id="fu-obj" />
<div data-file-upload><!-- Output here: "True" Or "False" if file isset --></div>
<script>
// "fu" - file upload
var fu = {
response: document.querySelector('[data-file-upload]'),
ele: document.querySelector('[name="fu-obj"]')
};
fu['ele'].onblur = function() {
if(fu['ele'].files.length > 0) {
ajax.onreadystatechange = function() {
if(this.status === 200 && this.readyState === 4) {
fu['response'].innerHTML = this.responseText;
}
}
ajax.open('POST', 'post.php', true);
ajax.setRequestHeader('Content-type', 'multipart/form-data');
ajax.send('fu-obj='+fu['ele'].files[0].name);
}
}
</script>
<!-- If ajax doesn't work -->
<button type="submit">Manual Upload</button>
</form>
- the
post.php
file is really simple and don't do yet any action, only contains anif()
statementif(isset($_POST['fu-obj'])) { echo 'True'; } else { echo 'False'; }
to check if it works
UPDATE I've replaced $_POST
with $_FILES
, when I send it manually it works (but not with ajax)
UPDATE 2 - ajax.js:
var ajax;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
}
else {
// Microsoft IE (5,6)
ajax = new ActiveXObject();
}
How can I solve this issue? Thank you very much!
(Please, don't suggest jQuery solutions, even if it's easier)