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;
}
6
  • Weird, I just tested AJAX with print_r ($_POST) and could retrieve the result just fine. Maybe post the full code you're using? Commented Oct 14, 2015 at 20:18
  • @GGG Updated, adding encodeURIComponent() doesn't seem to do any good. Commented Oct 14, 2015 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. Commented Oct 14, 2015 at 20:27
  • @GGG Okay, working on it... Commented Oct 14, 2015 at 20:28
  • Also, you'll need to iterate through the files as FormData doesn't does that. Commented Oct 14, 2015 at 20:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.