$ _POST and $ _FILES empty after uploading the AJAX file

I am new to web development and the last problem I ran into was loading the ajax file ...

I now have two HTML input fields; file input and button.

<input type="file" name="Frame" id="Frame_"/>
<input type="button" name="FrameButton" id="FrameButton_" value="UPLOAD"/>
      

Run codeHide result


After clicking the button, I call the function which has the following code.

var frame = document.getElementById('Frame_');
var frameImg = frame.files[0];
var form_data = new FormData();

form_data.append('frame', frameImg);

jQuery.ajax({
    url : './handler.php',
    type : 'post',
    data  :  form_data
    contentType : false,
    processData : false,
    success : alert("Frame Uploaded")
});
      

Run codeHide result


When I var_dump () the $ _POST and $ _FILES array, it shows both arrays as empty. This is despite the "Request for Payload" in the Chrome Dev reading

Content-Disposition: form-data; name = "frame"; filename = "GoldFrame.jpg"

Content-Type: image / jpeg

In which I am under the impression that this means that the information about the file I select from the front panel is successfully "sent" to the handler.php file. Is this a misinterpretation?

Anyway, can someone please give me an answer to my problem? Or at least point out a resource my answer may have? There seems to be a lot of similar questions along the same lines, but I haven't seen one that has a solid answer.

I've used iframes for this kind of thing in the past, but it seems like a really hacky technique and I would like to have the flexibility to use ajax for this task in the future.

Help is appreciated.

+3


source to share


2 answers


Try it.

Form (index.html)

<form id="uploadForm">
    <input type="file" name="frame" />
    <input type="submit" value="UPLOAD" />
</form>

      

Script (script.js)



$("#uploadForm").on('submit',(function(e) {
    e.preventDefault();
    $.ajax({
        url: "handler.php",
        type: "POST",
        data:  new FormData(this),
        contentType: false,
        cache: false,
        processData: false,
        success: function(data){
            console.log(data);
        }           
    });
}));

      

Server side (handler.php)

<?php 

var_dump($_FILES);

      

+2


source


You var_dump () - your $ _FILES / $ _ POST arrays in handler.php file?

If you try to dump these variables in a file with an ajax call, it won't work because AJAX makes the frontend and the files / post variables are server side variables ... which means only the handler.php file will have those variables.



Try adding a var_dump () call to handler.php and output that will result in an ajax call and I hope you see the results you are looking for.

0


source







All Articles