Skip to content
Advertisement

fetch formdata response from php server

I understand that fetch() response lets you receive formData from a server. I searched for an example that implements this functionality but I didn’t find a single one. All examples talk about uploading (posting) formData from a client to a server, but not vice versa. This doesn’t explain the .formData() method of the response.

So, could you please direct me to any link that has an example that receives a form data from a PHP server using the .formData() method of a fetch() response.

Thank you

Advertisement

Answer

https://developer.mozilla.org/en-US/docs/Web/API/Body/formData demonstrates the basic idea:

response.formData()
.then(function(formdata) {
  // do something with your formdata
});

But it’s very unusual for a server to return data in formData format – I’ve never seen that happen. It’s not actually a very convenient format when it’s serialised. Normally a server will return plain text, HTML, JSON or XML (or binary file data, of course).

The “note” in yellow at the top of the documentation explains what it’s mainly used for. It says:

This is mainly relevant to service workers. If a user submits a form and a service worker intercepts the request, you could for example call formData() on it to obtain a key-value map, modify some fields, then send the form onwards to the server (or use it locally).

(It’s important to realise that this can read from the body of an outgoing request as as well as an incoming response. And also that the comparable text(), json() blob() etc methods can all be used in both directions too – these methods are attached to the Body object. Both requests and responses can contain a Body. So actually these methods don’t care if it’s a request or a response, they simply try to read from the Body of whatever it happens to be.)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement