Birrel
Birrel

Reputation: 4834

Only JQuery working with FormData?

I am sending form contents via an AJAX call.

The form is:

<form id="id_of_form" enctype="multipart/form-data">
  <input type="text" name="name" id="name" />
  <input type="file" name="fileField" id="fileField" />
  <br/><br/>
  <input class="button" type="submit" value="Upload"/>
</form>

My preferred method is the following:

Method 1

<script type="text/javascript">

$(document).ready(function(){
    $('#id_of_form').on('submit',function(e){
        e.preventDefault();

        var formdata = new FormData($(this)[0]);      

        var ajax = new XMLHttpRequest();
        ajax.open("POST", "testing.php", true);

        ajax.onreadystatechange = function(){
            if(ajax.readyState == 4 && ajax.status == 200){
                var returnVal = ajax.responseText;

                ... do stuff here ...
            }
        }
        ajax.send(formdata);
    });
});

</script>

This sorta works. In my PHP, if($_POST) returns TRUE, but if($_FILES) returns FALSE (when both the name and file field contain something). When I do var_dump($_POST) in my PHP, it spits out the following:

array(312) { ["------WebKitFormBoundaryoypwTdV9MSCqJC2F Content-Disposition:_form-data;_name"]=> string(5698) ""name" qwert ------WebKitFormBoundaryoypwTdV9MSCqJC2F Content-Disposition: form-data; name="fileField"; filename="carved-coral-beads.jpg" Content-Type: image/jpeg ���� VExifMM* ���=�19(1A2_��s������i ��SA

^ Only an abbreviation - actually MUCH longer.

var_dump($_FILES) returns

array(0) { }

Method 1 only works when I send data in the following way:

ajax.send("username=something&var2=somethingelse");

but I can't include any files (specifically, an image) in this way.

If I use JQuery to send it:

Method 2

<script type="text/javascript">

$(document).ready(function(){
    $('#id_of_form').on('submit',function(e){
        e.preventDefault();

        var formdata = new FormData($(this)[0]);

        $.ajax({
            url: "testing.php", 
            type: "POST",    
            data: formdata, 
            contentType: false,
            cache: false,      
            processData:false, 
            success: function(data){
                ... do stuff here ...
        }
    });
});

</script>

it works just fine, and I can parse the contents and file in my PHP.

Just out of habit, I would like to use the Method 1. Why will Method 2 with the JQuery version work just fine, but the first method flops?

Thanks in advance.

Upvotes: 2

Views: 1463

Answers (1)

Kevin
Kevin

Reputation: 41885

Yes, it'll work just fine also, the one line you pointed out doesn't work since you have a variable typo on Method #1:

var formdata = new FormData($(this)[0]);
ajax.send(formData); // formdata != formData

Sidenote: I can't setup a demo yet, http://codepad.viper-7.com I think is still down (at least on my end). I'll set it up later once I can access but here's what I would have used.

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    print_r($_FILES);
    print_r($_POST);
    exit;
}

?>

<form id="id_of_form" enctype="multipart/form-data">
  <input type="text" name="name" id="name" />
  <input type="file" name="fileField" id="fileField" />
  <br/><br/>
  <input class="button" type="submit" value="Upload"/>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('#id_of_form').on('submit',function(e){
        e.preventDefault();

        var formdata = new FormData($(this)[0]);
        var name_value = document.getElementById('name').value;
        formdata.append('name', name_value);  // append value

        var ajax = new XMLHttpRequest();
        ajax.open("POST", document.URL, true);


        ajax.onreadystatechange = function(){
            if(ajax.readyState == 4 && ajax.status == 200){
                var returnVal = ajax.responseText;
                console.log(returnVal);
            }
        }
        ajax.send(formdata);
    });
});
</script>

Important Note: Handle $_FILES for your uploaded file and handle $_POST for your text inputs.

Upvotes: 2

Related Questions