fetch formdata response from php server - javascript

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

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

Related

When using the Fetch API, why do post requests require more inputs than a get request?

How come when we use the Fetch API, it requires a significant amount of more input into the function for a POST request as opposed to a GET request. This has been a bit of a learning curve for myself. Also, what determines the headers you need to use for a POST request?
TLDR, POST has more stuff to it.
GET and POST are methods for HTTP Requests. The main ones of interest are:
GET: get a thing
POST: make a new thing
PUT: change a thing
DELETE: delete a thing
The most basic form of a GET is asking a specific URI to send back pre-set data. Also, GET tends to be the most common use request so most HTTP request-making methods will make this very simple. Thus, GET is often done with little more than a URI.
In contrast, POST has a lot going on.
You aren't making a GET request. This is more specific to Fetch API as it assumes GET by default so you need to specify in the options that you are using method: "POST".
You are, by definition, sending data. Therefore, you must include that data in the method: body: myData
Data has a format. The server has no idea if you sent it a string, and integer, a JSON, or the whole Harry Potter movie set. It just sees a stream of 1s and 0s. This is where headers come in, which let you specify to the server that you are sending it a JSON object or an image file so that the server can appropriately deal with the bits. Thus, we see headers: { 'Content-Type': <MIME type of myData> } in the options.

I'm trying to send a JSON object from client to server and receive a response but all the approaches I find are either inadequate or overkill

I'm in a situation where I'm not sure what is the correct way of doing this. I'm trying to take a large json file, send it to the server, process and reorder it, and then send it back to the client. I don't want to store any data in a database. I know there's the HTTP GET verb, but the amount of data I would be inputting would be longer than the max length URI. I also read that you shouldn't try to do this with a HTTP POST either.
I looked into WebSockets as well but to me it appears to be overkill. I would only need the socket for the time that it takes to do the computations, then I would close it. Also I want to share the data with only the client who sent it to me.
Does any one have recommendations as for what to do. Maybe just a push in the right direction with a few links I can read. I'm really looking for something that runs down the middle of these two methods.
Why don't you just use a HTTP POST request? Taken from an info box on
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
> Request has body Yes
> Successful response has body Yes
> Safe No
> Idempotent No
> Cacheable Only if freshness information is included
> Allowed in HTML forms Yes
As you see, a HTTP POST request is used for sending data to the server, and if the POST request was successful, the server sends data back to the client. Perfect for your situation, I think.
A POST request doesn't have to be used within a HTML form; you could use XHR, AJAX, the fetch API, or any other way you can find to send the server a POST request. And yes, you could send JSON data with it.
If you need more convincing:
When the POST request is sent via a method other than an HTML form — like via an XMLHttpRequest — the body can take any type. As described in the HTTP 1.1 specification, POST is designed to allow a uniform method to cover the following functions:
Annotation of existing resources
Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
Adding a new user through a signup modal;
Providing a block of data, such as the result of submitting a form, to a data-handling process;
Extending a database through an append operation.
Notice that there, it said that a POST request can be used to provide a block of data to a data-handling process.
Hope this helps you. :)

can AJAX do anything else than load a JSON file?

I'm want to (or think I need to) use AJAX to accomplish what I intend.
When clicking on a specific link in a list of links, I want to fill the HTML markup below with content of specific subpages. The data is naturally somewhere in the database and actually easily accessible with the CMS's API (I'm using Processwire).
I'm quite new to coding and especially AJAX and all documentation I find online only mention it in combination with a JSON file that would be loaded via AJAX.
However, I don't have a JSON file on the server, that means, according to my understanding, I would need to
store the data I need in a multidimensional php array,
use json_decode to create and then save that JSON-file on the server,
load that file via AJAX and process through more JS.
Let alone keep that JSON-file updated (or create a new one and delete the old one?) since new content will arrive periodically. It seems unnecessarily complicated to me, but what do I know.
There's got to be a better way…
Any help is appreciated.
AJAX is simply a way to make a request to the web server for information.
When you make an AJAX request you ask for a response from a file on a server. So, you can send an AJAX request to a PHP script for-instance.
The PHP script could return anything, JSON is common and very widely used response format, but XML might be another one you've encountered.
So, your request for information is made using AJAX, and the response you get back is JSON.
You don't need to store a JSON file on your server. You just need to make an AJAX request that returns current data in JSON format.
AJAX allows you to do asynchronous HTTP requests.
You can of course ask for a json file, but you can also (for example) call an API.
I suggest you start by reading the the getting started guide for AJAX in MDN:
https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started

Why is it safe to send Array of File Objects via Ajax but not via a regular Http Request?

I use an HTML form to allow the user to upload files.
In order to make adding attachments more user friendly, I added client side code to allow the user to add/remove files (I basically did this as outlined in this answer).
Because I don't want to adjust too much of my server side code, I'd still like to send the form in a regular request, handle it on my server, and return an Http Response (ie: no Ajax, send request from same thread as main page and then redirect or forward the response on my Servlet).
However, the only way to submit the FormData Object is via Ajax.
When I look for ways to send the FormData Object via a regular Http Request (eg: by attaching it to the form), I hear that this is not allowed because it is not safe.
Why can the FormData be submitted via XMLHttpRequest but submitting via regular Http Request (like a regular form submit) is considered not safe to the user? What's the difference?
To phrase this another way: You can mess with attachments if you're submitting them via Ajax but not via a regular request. Why?
If there is a way to submit the FormData in a regular request, I would be interested to hear what it is.
Thanks.
Extra clarification (motivated by comments):
The input element on the form does not accurately represent the user's selections. I allow the user to add/remove files. I do this by creating my own Array of File Objects in the client side code. This new array of File Objects needs to be sent with the request. This is possible with Ajax (ie: by creating a FormData Object), not with regular form submit; why?
The only way to submit the FormData Object is via Ajax
This is not true.
A FormData object is simply a way of encoding binary data before transfer (see MDN for a full outline of its purpose). It is only really required when sending files (ie. binary data) to the server.
If you want to do that without AJAX, add the enctype="multipart/form-data" attribute to your form element and submit it as usual.
Also note that the use of FormData has nothing to do with security, as your question title implies.

what's the diffrence between $.ajax / $.get / $.POST / .load()?

I'm trying to understand AJAX and JSON and I'm not sure I get it, there are methods and functions that are doing the same stuff...
You've got $.getJSON to retrieve JSON format data from server, and you have $.ajax + $.post + $.get + load() to send data data to the server?
Can I use all of those methods to send JSON data?
Really I'm confused! Help me figure this out.
All those are just shorthands for calling the $.ajax function.
load is for retrieving HTML and writing it to the DOM in one go. You want to load JSON.
get and getJSON use GET requests which are not well-suited for sending JSON data.
post does a POST request, but doesn't allow you to choose the contentType of the sent data
For sending JSON you should use the $.ajax function with its many options, see Send JSON data with jQuery.
An AJAX request is, at heart, an HTTP request. This is the same protocol which is used for all content on the Web (arguably, if it's not HTTP, it's not the Web) - loading a page, the images on the page, the CSS and JS includes, a submitted form, etc, etc.
As such, it inherits pretty much all of the flexibility of HTTP, meaning a generic function like jQuery.ajax ends up quite complex, with lots of options you don't normally need to worry about. This leads to the Shorthand Methods you mentioned, which bundle up common sets of options and functionality.
Among the things you might want to vary:
The "method" of the request: GET or POST (or less common ones like HEAD, PUT, DELETE...). A GET request is the simplest: request this URL, give me its contents; parameters to a GET request are shoved onto the "query string" of the URL. A POST request is how larger forms would be submitted on a normal page: the parameters are passed as a body of data separate from the URL and control headers; for an AJAX request this is often helpful to send a block of XML or JSON to a URL. This is a very broad overview, and there are many more distinctions in behaviour and meaning between the two.
The "content type" you want in the response (and, for a POST request, of the data you're sending). Not only does this tell both the server and the browser what data it is handling, ensuring it will pass it successfully, it can give jQuery (or whatever library) a hint of what to do next: if a call returns XML, you'll probably want to manipulate it as a DOM straight away; if it's JSON, you'll want to parse it as a JS object.
What you want to do once the data comes back. I've already mentioned parsing JSON or XML, but what if your response is actually a block of HTML that you want to inject straight into the parent page? Obviously you could do that yourself in the callback function, but again jQuery includes a shorthand form in the shape of .load().
All of the above are possible with jQuery.ajax, but you'd have to remember the parameters, even though you're falling into the same cases again and again, so chances are most of the time you'll be using whichever of the shorthands suits your needs at that moment.

Categories

Resources