aweeeezy
aweeeezy

Reputation: 876

Can't figure out how to POST form data to php with $.ajax

EDIT: * updated code to reflect state and current issue *

My HTML form is properly accepting the input[type=file]. I know I'm appending the proper data (file.name) to formData. I know my script archive_upload.php is being called, but this is where things go wrong. $_POST doesn't seem to be taking in any thing. If I print $len after $len = (int) $_POST['CONTENT_LENGTH'];, it shows 0.

How can I properly retrieve the FormData being sent to my script?

Here's my JS:

var formData = new FormData();
var fileSelect = document.getElementById('file');
var uploadButton = document.getElementById('upload');
var form = document.getElementById('file_form');
/*$('#file').change(function() { });*/
form.onsubmit = function(event) {
    event.preventDefault();
    var files = fileSelect.files;

    for (var i=0; i<files.length; i++) {
        var file = files[i];
        if(!file.type.match('image.*')) {
            continue;
        }
        formData.append(i, file.name);
    }
    xhr = new XMLHttpRequest();
    xhr.open('POST', 'archive_upload.php');
    xhr.send(formData);
}

Here's my HTML:

<form id="file_form" action="archive_upload.php" method=POST  enctype=multipart/form-data accept-charset=utf-8>
    <input type="file" id="file" name="photos[]" />
    <button type="submit" id="upload">Upload</button>
</form>

And the PHP:

<?php
    $len = (int) $_POST['CONTENT_LENGTH'];
    $files = array();
    for ($i=0; $i < $len; $i++) {
        $f = $_POST[$i]['name'];
        $files.append($f);
    }
    $j = fopen('test.json', 'w');
    fwrite($j, json_encode($files));
    fclose($j);
?>

Upvotes: 0

Views: 638

Answers (2)

Ajay Gupta
Ajay Gupta

Reputation: 1285

Since you are using Html form and ajax for submitting the form data, the simplest way would be something like this :

<script>
$(document).ready(function(){
    $("#upload").click(function(){
        $.ajax({url: "<your url>",
                data: {<put your data here>}
                success: function(result){

                }
                cache: false,
                contentType: false,
                processData: false
    });
    });
});
</script>

HTML form:

<form id="file_form" action="archive_upload.php" method=POST  enctype=multipart/form-data accept-charset=utf-8>
    <input type="file" id="file" name="photos[]" />
    <button type="button" id="upload">Upload</button>
</form>

Upvotes: 1

Gregory Nikitas
Gregory Nikitas

Reputation: 491

From what I understand it is not calling the ajax page at all, therefore consider adding the following code snippet as options in your ajax call:

processData: false,
contentType: false,

I believe this post has experience in a similar issue with file[s] and FormData

Upvotes: 1

Related Questions