JavaScript Async - The Fetch API
JavaScript Async - The Fetch API
Written by Ian Elliot   
Monday, 16 October 2017
Article Index
JavaScript Async - The Fetch API
FormData, Get & Post

 

coverasync

 

 

FormData, Get & Post

 

The most common fetch operations that go beyond a simple get are get with a query string and posting form data. Let’s see how to do both of these tasks.

The data that we want to send could come from anywhere, but a traditional form element is simple and common:

<form id="myForm" >
  First name:<br>
  <input type="text" name="first" value="Enter Data">
  <br>
  Last name:<br>
  <input type="text" name="last" value="Enter Data">
  <br>
  <br>
  <input type="submit" value="Submit">
</form>

Now all we need is to handle the submit event:

myForm.addEventListener('submit',
   function (event) {
      event.preventDefault();
      sendData();
   });

 

The sendData function does the actual work using fetch but first we need to construct a query string that can be added to the URL. It is strange that JavaScript has had no standard way of doing this until recently and at the moment not all browsers support the new features. If you don’t want to use the new FormData and URL APIs then your best option is either to do the job directly, use a polyfill or use jQuery:

async function sendData() {
  var url = new URL("http://url/myFile.php");
  var formdata = new FormData(myForm);
  for (var p of formdata) {
    url.searchParams.append(p[0], p[1]);
  }
 var request = new Request(url, { method: "GET" });
 console.log(url.toString());
 var response = await fetch(request);

 

The FormData object creates a set of key/value pairs from the form with the keys being the id’s and the values being what ever the user entered. This is then converted to a query string using the searchParams method of the URL object. Finally we build a request object specifying a GET and perform the fetch.

The url is something like:

http://url/myFile.php?first=Mickey&last=Mouse

assuming that the user entered Mickey Mouse as the first and last names. This is sent to the server, which will process it and do whatever is appropriate with the data before returning a response. This can either be collected using a command like:

await response.text();

or we can opt to ignore it.

 

Sending form data using a POST is even easier as we can send a FormData object without having to convert it:

async function sendData() {
 var url = new URL("http://url/myFile.php");
 var formdata = new FormData(myForm);
 var request = new Request(url, { method: "POST",
                                  body: formdata });
 var response = await fetch(request);

The formdata will be unpacked into the body and sent to the server. A Content header is also set automatically so that the server can check the format of the data.

Notice that as a Request object has a body you can access it using the same methods as in a Response object. As for the Response object, once you have used the body data you can’t use it a second time. You can, of course, clone it if you really want to treat it as different formats.

This is about all there is to know about the new APIs. There are still things to learn and implement, but these problems are not any different from using other methods of transferring data. Currently the facilities offered by fetch aren’t as extensive as what you will find in, say, jQuery, but it has to be taken into account that fetch is the way of the future.

There are also some new features in the Fetch API that help with the problem of canceling and controlling a request, the Abort API, but these aren’t standardized as yet. In addition, it is worth knowing that you can access the lower level data streams used to access the body data. This offers the possibility of creating very sophisticated processing.  However, in most cases the standard formatted stream readers are enough. 

 

Now Available as a Print Book:

 JavaScript Async

cover

You can buy it from:

USA and World     Amazon.com
Canada            Amazon.ca

UK                Amazon.co.uk
France            Amazon.fr
Germany           Amazon.de
Spain             Amazon.es
Italy             Amazon.it
India             Amazon.in
Japan             Amazon.co.jp

 

 

Contents

  1. Modern JavaScript (Book Only)
  2. Events,Standard & Custom
  3. The Callback 
  4. Custom Async - setTimeout, sendMessage & yield
  5. Worker Threads
  6. Consuming Promises
  7. Producing Promises
  8. The Dispatch Queue
  9. Async & Await
  10. Fetch, Cache & Service Worker
    extract 1 - Fetch   ***NEW

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on, Twitter, FacebookGoogle+ or Linkedin.

 
 

 

blog comments powered by Disqus

 <ASIN:1871962528>

<ASIN:1871962501>

 



Last Updated ( Tuesday, 17 October 2017 )
 
 

   
Banner
RSS feed of all content
I Programmer - full contents
Copyright © 2017 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.