phpajaxxmlhttprequest-level2

PHP handle $_POST from XMLHttpRequest2 with new FormData() and append()


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;
}

Solution

  • 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.