Load file with AJAX & PHP - $ _FILES array is empty

I've read about 20 different questions / answers in the forum / stackoverflow about this, but I just can't get it to work. I've been working with jQuery / PHP for about 5 years, but this is the first time I need to do something like this with AJAX.

So ... for now I'm just testing and trying to load the .txt file and try to get its content with file_get_contents()

and send it back to my JS code.

I removed all the fancy co-workers 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)

that gives me an empty array.

My JS and form are copied from one of the stackoverflow answers. URL: $ _ POST and $ _FILES is empty after uploading the AJAX file - because it's flagged as it works, but for me ... still empty.

Usually my form has enctype="multipart/form-data"

and method="post"

, but it makes 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 I can't try anymore, no matter what I do, the array is $_FILES

empty.

+3


source to share


2 answers


Your AJAX logic is fine. The problem is that you are using a very, very outdated version of jQuery, and there have been a lot of tweaks for AJAX logic over the years of development, especially since it supports supporting FormData

and sending binary data via AJAX.



You should update jQuery to at least 1.12, ideally 3.2 unless you need legacy IE support.

+2


source


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 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>

      

0


source







All Articles