简体   繁体   中英

PHP - multipart/form-data variables returns NULL when parsing a FormData from jQuery (AJAX)

Scenario

From Js I create a dynamic FormData Object and then I post the data with $.ajax() to a PHP.

Problem

I can't access the variables in PHP

var_dump($_POST['name']); // This returns NULL

NULL

But! this shows the Array(), so the data is there

var_dump($_POST); // This shows the full array()

array(1) {
  ["------WebKitFormBoundarybLgHYUQw1augDdyF
Content-Disposition:_form-data;_name"]=>
  string(161) ""author"

test
------WebKitFormBoundarybLgHYUQw1augDdyF
Content-Disposition: form-data; name="name"

jon snow
------WebKitFormBoundarybLgHYUQw1augDdyF--
"
}

Edit: This works too

foreach($_POST as $key=>$value)
{
  echo "$key=$value";
}

Log:

------WebKitFormBoundarycozyxlP96SxBy3O0
Content-Disposition:_form-data;_name="author"

test
------WebKitFormBoundarycozyxlP96SxBy3O0
Content-Disposition: form-data; name="name"

jon snow
------WebKitFormBoundarycozyxlP96SxBy3O0--

update

foreach($_POST as $key=>$value)
{
  var_dump($key);
}
?>

Log $key:

string(78) "------WebKitFormBoundaryK2sJT1BCmNt5jVVW
Content-Disposition:_form-data;_name"

//

foreach($_POST as $key=>$value)
{
  var_dump($key);
}
?>

Log $value;

string(161) ""author"

test
------WebKitFormBoundaryosBAfp5AzD7g7fly
Content-Disposition: form-data; name="name"

jon snow
------WebKitFormBoundaryosBAfp5AzD7g7fly--

The Js methods

Rimodromo.prototype.collectData = function(audio, sound, author) {
    var newPoemStore = rimodromo.newPoem;

    formData = new FormData();

    // formData.append("rime", newPoemStore);
    // formData.append("audio", new Blob([recorder.blob], {type:"application/octet-stream"}));
    // formData.append("sound", rimodromo.selectedSound);
    formData.append("author", "test");
    formData.append("name", "jon snow");


    // var myData = {
    //     rime:newPoemStore, 
    //     audio:recorder.blob,
    //     sound:rimodromo.selectedSound, 
    //     author:author || 'anónimo',
    //     name:name || 'nombre de rima'
    // }
    // return myData;
    return formData;
};



Rimodromo.prototype.submitRimodromo = function() {
    var myData = rimodromo.collectData();
    for (var pair of myData.entries()) {
        console.log(pair[0]+ ', ' + pair[1]); 
    }
      $.ajax({
        url : "insert.php",
        type: "POST",
        data: myData,
        cache: false,
        contenType: false,
        processData: false,
        success: function(data,status,xhr) {
            console.log(data);
            console.log(status);
        }

      }); 


};

Any clues? Thanks in advance =)

I've tried it in the past, but sometimes it worked and sometimes it did not work. This is due to the configurations, that we have to give to data to be send by ajax, for getting the file upload working.

I recently found a method, which I'll try for next week in a project I'm currently working on.

This method its base on a plugin is found in this link: How do I capture response of form.submit

From what I have read it still does not work on browsers that do not support html 5, but this is no different than what happens with an ajax upload.

For more information use this link: http://malsup.com/jquery/form/#file-upload

FRONT END:

 <form id="myForm" action="upload.php" method="post" enctype="multipart/form-data"> 
        <input type="file" name="fileToUpload" id="fileToUpload"> 
        <input type="submit" value="Submit Comment" /> 
    </form>

 <script> 
        // wait for the DOM to be loaded 
        $(document).ready(function(e) { 
            e.preventDefault();
            // bind 'myForm' and provide a simple callback function 
            $('#myForm').ajaxForm(function() { 
                url : 'myscript.php', // or whatever
                success : function (response) {
                   alert("The server says: " + response);
                } 
            }); 
        }); 
    </script> 
</head> 
...

SERVER SIDE:

    <?php
      ... //your code for testing the file exist, type and size 
       // if everything is ok, try to upload file
           if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
            } else {
                     echo  "Sorry, there was an error uploading your file.";
             }
?>

I hope it helps!

Finally the error was a typo:

contenType: false,

must be:

contentType: false,

that fix the error!

¯\_(ツ)_/¯

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM