Reputation: 390
I have read close to 20 different forum post/stackoverflow questions/answers about this but I just can't get this work. I've worked with jQuery/PHP about 5years now but this is first time when I need to do something like this with AJAX.
So... for now, I'm just testing and trying upload .txt file and try get the contents of it by using file_get_contents()
and send it back to my JS code.
I have removed all fancy staff and simplified my files as much as I could, so this is my HTML file:
<div class="container-fluid">
<div class="row">
<div class="col-xs-12">
<form id="uploadForm" action="url/to/php/script">
<input type="file" name="frame" />
<input type="submit" value="UPLOAD" />
</form>
</div>
</div>
</div>
and my JS
$("#uploadForm").bind('submit',(function(e) {
e.preventDefault();
$.ajax({
url: 'url/to/php/script',
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log(data);
}
});
}));
and in my PHP script I have var_dump($_FILES)
which gives me empty array.
My JS & form are copied from one of the stackoverflow's answers. URL: $_POST and $_FILES empty after AJAX file upload - because it's marked as it works but for me... still empty.
Normally my form have enctype="multipart/form-data"
and method="post"
but theres no difference.
My jQuery lib: http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js
I came here because I feel like there's no more things I could try, no matter what I do, $_FILES
array is empty.
Upvotes: 2
Views: 2069
Reputation: 5690
use new version jquery library like this, your ajax code looks good so for this requirement need to update your jquery library . you use old library in that case it is not working
http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js
more for information
https://code.jquery.com/jquery/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "url/to/php/script",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
}
});
}));
</script>
Upvotes: 0
Reputation: 337560
Your AJAX logic is fine. The issue is because you're using a very, very outdated version of jQuery, and there have been many tweaks to the AJAX logic over the years of development - especially since the rise in support for FormData
and sending binary data via AJAX.
You should upgrade jQuery to at least 1.12, ideally 3.2 if you don't need legacy IE support.
Upvotes: 2