1

Using PHP how can I process data sent via XMLHttpRequest2 with new FormData() and append() like traditional form data?

In my AJAX parameters handling function the parameters would look like the following:

q1=v1&q2=v2&q3=v3

You could use print_r($_POST); and determine to access $_POST['q1'] to get the value v1 easily.


While testing XMLHttpRequest2 with new FormData() and append() on the server when I have PHP and use print_r($_POST); I get the following:

-----------------------------3875113001076
Content-Disposition: form-data; name="q1"
v1

-----------------------------3875113001076
Content-Disposition: form-data; name="q2"
v2

-----------------------------3875113001076
Content-Disposition: form-data; name="q3"
v3

However I can no longer access $_POST['q1'];.


JavaScript AJAX Parameters Function

function ajax_parameters(id)
{
 var f;
 var fd = new FormData();

 if (id_(id) || typeof id=='object' && id.nodeName.toLowerCase()=='form')
 {
  if (id_(id)) {f = id_(id);}
  else {f = id;}

  for (var i = 0;i<f.elements.length;i++)
  {
   if (f.elements[i].type!='file')
   {
    fd.append(f.elements[i].name,f.elements[i].value);
   }
   else
   {
    for (var j = 0; j < f.elements[i].files.length; ++j)
    {
     fd.append(f.elements[i].name+'['+j+']', f.elements[i].files[j],f.elements[i].files.item(j).name);
    }
   }
  }
 }
 return fd;
}
John
  • 1
  • 13
  • 98
  • 177
  • Weird, I just tested AJAX with `print_r ($_POST)` and could retrieve the result just fine. Maybe post the full code you're using? – GGG Oct 14 '15 at 20:18
  • @GGG Updated, adding `encodeURIComponent()` doesn't seem to do any good. – John Oct 14 '15 at 20:27
  • 1
    You're able to use `new FormData(id)` to create the FormData if the `id` is the form element. No need to iterate through all elements of the form since FormData can do that by itself. – GGG Oct 14 '15 at 20:27
  • @GGG Okay, working on it... – John Oct 14 '15 at 20:28
  • Also, you'll need to iterate through the files as FormData doesn't does that. – GGG Oct 14 '15 at 20:35
  • I wrote a minimal test case and it worked. Removing `xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');` from the main `AJAX` function resolved the issue which is odd since I was certain it was required when you have file uploads in XMLHttpRequest2 but whatever. Please post your second comment as an answer and I'll gladly accept and comment how it worked for me for others to benefit from. :-) – John Oct 14 '15 at 20:39

1 Answers1

1

You're able to use new FormData(id) to create the FormData if the id is the form element. No need to iterate through all elements of the form since FormData can do that by itself.

GGG
  • 640
  • 1
  • 9
  • 27
  • Firefox 38 ESR apparently automatically determines the correct mime (`application/x-www-form-urlencoded ` or `multipart/form-data`) but I'll need to test. Visit my profile/site to see what you're contributing to and thanks! – John Oct 14 '15 at 20:44