0

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

tourdefran
  • 71
  • 1
  • 7
  • 1
    the problem is with the key? you need to pass the total key in $_POST to get the name like $_POST["------WebKitFormBoundarybLgHYUQw1augDdyF Content-Disposition:_form-data;_name"] – Exprator May 13 '17 at 05:38
  • HI, please look at the edit, Can you please post some example to achieve that? – tourdefran May 13 '17 at 18:34
  • Print the key and value and show the output – Exprator May 14 '17 at 03:28
  • Thanks Exprator, please see the **update** in my question, Looks like the quotes are breaking the structure somehow! – tourdefran May 15 '17 at 17:47

2 Answers2

0

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!

Community
  • 1
  • 1
Jose Marques
  • 748
  • 1
  • 6
  • 22
  • Thanks, but I don't have a form in my markup, I create it with FormData(). I need to get the vars from the php to then post them to the db – tourdefran May 13 '17 at 18:21
0

Finally the error was a typo:

contenType: false,

must be:

contentType: false,

that fix the error!

¯\_(ツ)_/¯
tourdefran
  • 71
  • 1
  • 7