Sending forms through JavaScript

HTML forms can send an HTTP request declaratively. But forms can also prepare an HTTP request to send via JavaScript, for example via XMLHttpRequest . This article explores such approaches.

A form is not always a form

With progressive web apps, single page apps, and framework based apps, it's common to use HTML 表单 to send data without loading a new document when response data is received. Let's first talk about why this requires a different approach.

Gaining control of the global interface

Standard HTML form submission, as described in the previous article, loads the URL where the data was sent, which means the browser window navigates with a full page load. Avoiding a full page load can provide a smoother experience by avoiding network lag, and possible visual issues like flickering.

Many modern UIs only use HTML forms to collect input from the user, and not for data submission. When the user tries to send the data, the application takes control and transmits the data asynchronously in the background, updating only the parts of the UI that require changes.

Sending arbitrary data asynchronously is generally called AJAX , which stands for "Asynchronous JavaScript And XML" .

How is it different?

XMLHttpRequest (XHR) DOM object can build HTTP requests, send them, and retrieve their results. Historically, XMLHttpRequest was designed to fetch and send XML as an exchange format, which has since been superseded by JSON . But neither XML nor JSON fit into form data request encoding. Form data ( application/x-www-form-urlencoded ) is made of URL-encoded lists of key/value pairs. For transmitting binary data, the HTTP request is reshaped into multipart/form-data .

注意: 抓取 API is often used in place of XHR these days — it is a modern, updated version of XHR, which works in a similar fashion but has some advantages. Most of the XHR code you'll see in this article could be swapped out for Fetch.

If you control the front-end (the code that's executed in the browser) and the back-end (the code which is executed on the server), you can send JSON/XML and process them however you want.

But if you want to use a third party service, you need to send the data in the format the services require.

So how should we send such data? The different techniques you'll require are done below.

Sending form data

There are 3 ways to send form data:

  • Building an XMLHttpRequest manually.
  • Using a standalone FormData 对象。
  • 使用 FormData bound to a <form> 元素。

Let's look at them in detail.

Building an XMLHttpRequest manually

XMLHttpRequest is the safest and most reliable way to make HTTP requests. To send form data with XMLHttpRequest , prepare the data by URL-encoding it, and obey the specifics of form data requests.

Let's look at an example:

<button>Click Me!</button>

					

And now the JavaScript:

const btn = document.querySelector('button');
function sendData( data ) {
  console.log( 'Sending data' );
  const XHR = new XMLHttpRequest();
  let urlEncodedData = "",
      urlEncodedDataPairs = [],
      name;
  // Turn the data object into an array of URL-encoded key/value pairs.
  for( name in data ) {
    urlEncodedDataPairs.push( encodeURIComponent( name ) + '=' + encodeURIComponent( data[name] ) );
  }
  // Combine the pairs into a single string and replace all %-encoded spaces to
  // the '+' character; matches the behavior of browser form submissions.
  urlEncodedData = urlEncodedDataPairs.join( '&' ).replace( /%20/g, '+' );
  // Define what happens on successful data submission
  XHR.addEventListener( 'load', function(event) {
    alert( 'Yeah! Data sent and response loaded.' );
  } );
  // Define what happens in case of error
  XHR.addEventListener( 'error', function(event) {
    alert( 'Oops! Something went wrong.' );
  } );
  // Set up our request
  XHR.open( 'POST', 'https://example.com/cors.php' );
  // Add the required HTTP header for form data POST requests
  XHR.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
  // Finally, send our data.
  XHR.send( urlEncodedData );
}
btn.addEventListener( 'click', function() {
  sendData( {test:'ok'} );
} )

					

Here's the live result:

注意: This use of XMLHttpRequest is subject to the same-origin policy if you want to send data to a third party web site. For cross-origin requests, you'll need CORS and HTTP access control .

Using XMLHttpRequest and the FormData object

Building an HTTP request by hand can be overwhelming. Fortunately, the XMLHttpRequest specification provides a newer, simpler way to handle form data requests with the FormData 对象。

FormData object can be used to build form data for transmission, or to get the data within a form element to manage how it's sent. Note that FormData objects are "write only", which means you can change them, but not retrieve their contents.

Using this object is detailed in Using FormData Objects , but here are two examples:

Using a standalone FormData object

<button>Click Me!</button>

					

You should be familiar with that HTML sample. Now for the JavaScript:

const btn = document.querySelector('button');
function sendData( data ) {
  const XHR = new XMLHttpRequest(),
        FD  = new FormData();
  // Push our data into our FormData object
  for( name in data ) {
    FD.append( name, data[ name ] );
  }
  // Define what happens on successful data submission
  XHR.addEventListener( 'load', function( event ) {
    alert( 'Yeah! Data sent and response loaded.' );
  } );
  // Define what happens in case of error
  XHR.addEventListener(' error', function( event ) {
    alert( 'Oops! Something went wrong.' );
  } );
  // Set up our request
  XHR.open( 'POST', 'https://example.com/cors.php' );
  // Send our FormData object; HTTP headers are set automatically
  XHR.send( FD );
}
btn.addEventListener( 'click', function()
  { sendData( {test:'ok'} );
} )

					

Here's the live result:

Using FormData bound to a form element

You can also bind a FormData object to an <form> element. This creates a FormData object that represents the data contained in the form.

The HTML is typical:

<form id="myForm">
  <label for="myName">Send me your name:</label>
  <input id="myName" name="name" value="John">
  <input type="submit" value="Send Me!">
</form>

					

But JavaScript takes over the form:

window.addEventListener( "load", function () {
  function sendData() {
    const XHR = new XMLHttpRequest();
    // Bind the FormData object and the form element
    const FD = new FormData( form );
    // Define what happens on successful data submission
    XHR.addEventListener( "load", function(event) {
      alert( event.target.responseText );
    } );
    // Define what happens in case of error
    XHR.addEventListener( "error", function( event ) {
      alert( 'Oops! Something went wrong.' );
    } );
    // Set up our request
    XHR.open( "POST", "https://example.com/cors.php" );
    // The data sent is what the user provided in the form
    XHR.send( FD );
  }
  // Access the form element...
  const form = document.getElementById( "myForm" );
  // ...and take over its submit event.
  form.addEventListener( "submit", function ( event ) {
    event.preventDefault();
    sendData();
  } );
} );

					

Here's the live result:

You can even get more involved with the process by using the form's 元素 property to get a list of all of the data elements in the form and manually manage them one at a time. To learn more about that, see the example in Accessing the element list's contents in HTMLFormElement.elements .

Dealing with binary data

If you use a FormData object with a form that includes <input type="file"> widgets, the data will be processed automatically. But to send binary data by hand, there's extra work to do.

There are many sources for binary data, including FileReader , Canvas ,和 WebRTC . Unfortunately, some legacy browsers can't access binary data or require complicated workarounds. To learn more about the FileReader API, see 使用来自 Web 应用程序的文件 .

The least complicated way of sending binary data is by using FormData 's append() method, demonstrated above. If you have to do it by hand, it's trickier.

In the following example, we use the FileReader API to access binary data and then build the multi-part form data request by hand:

<form id="theForm">
  <p>
    <label for="theText">text data:</label>
    <input id="theText" name="myText" value="Some text data" type="text">
  </p>
  <p>
    <label for="theFile">file data:</label>
    <input id="theFile" name="myFile" type="file">
  </p>
  <button>Send Me!</button>
</form>

					

As you see, the HTML is a standard <form> . There's nothing magical going on. The "magic" is in the JavaScript:

// Because we want to access DOM nodes,
// we initialize our script at page load.
window.addEventListener( 'load', function () {
  // These variables are used to store the form data
  const text = document.getElementById( "theText" );
  const file = {
        dom    : document.getElementById( "theFile" ),
        binary : null
      };
  // Use the FileReader API to access file content
  const reader = new FileReader();
  // Because FileReader is asynchronous, store its
  // result when it finishes to read the file
  reader.addEventListener( "load", function () {
    file.binary = reader.result;
  } );
  // At page load, if a file is already selected, read it.
  if( file.dom.files[0] ) {
    reader.readAsBinaryString( file.dom.files[0] );
  }
  // If not, read the file once the user selects it.
  file.dom.addEventListener( "change", function () {
    if( reader.readyState === FileReader.LOADING ) {
      reader.abort();
    }
    reader.readAsBinaryString( file.dom.files[0] );
  } );
  // sendData is our main function
  function sendData() {
    // If there is a selected file, wait it is read
    // If there is not, delay the execution of the function
    if( !file.binary && file.dom.files.length > 0 ) {
      setTimeout( sendData, 10 );
      return;
    }
    // To construct our multipart form data request,
    // We need an XMLHttpRequest instance
    const XHR = new XMLHttpRequest();
    // We need a separator to define each part of the request
    const boundary = "blob";
    // Store our body request in a string.
    let data = "";
    // So, if the user has selected a file
    if ( file.dom.files[0] ) {
      // Start a new part in our body's request
      data += "--" + boundary + "\r\n";
      // Describe it as form data
      data += 'content-disposition: form-data; '
      // Define the name of the form data
            + 'name="'         + file.dom.name          + '"; '
      // Provide the real name of the file
            + 'filename="'     + file.dom.files[0].name + '"\r\n';
      // And the MIME type of the file
      data += 'Content-Type: ' + file.dom.files[0].type + '\r\n';
      // There's a blank line between the metadata and the data
      data += '\r\n';
      // Append the binary data to our body's request
      data += file.binary + '\r\n';
    }
    // Text data is simpler
    // Start a new part in our body's request
    data += "--" + boundary + "\r\n";
    // Say it's form data, and name it
    data += 'content-disposition: form-data; name="' + text.name + '"\r\n';
    // There's a blank line between the metadata and the data
    data += '\r\n';
    // Append the text data to our body's request
    data += text.value + "\r\n";
    // Once we are done, "close" the body's request
    data += "--" + boundary + "--";
    // Define what happens on successful data submission
    XHR.addEventListener( 'load', function( event ) {
      alert( 'Yeah! Data sent and response loaded.' );
    } );
    // Define what happens in case of error
    XHR.addEventListener( 'error', function( event ) {
      alert( 'Oops! Something went wrong.' );
    } );
    // Set up our request
    XHR.open( 'POST', 'https://example.com/cors.php' );
    // Add the required HTTP header to handle a multipart form data POST request
    XHR.setRequestHeader( 'Content-Type','multipart/form-data; boundary=' + boundary );
    // And finally, send our data.
    XHR.send( data );
  }
  // Access our form...
  const form = document.getElementById( "theForm" );
  // ...to take over the submit event
  form.addEventListener( 'submit', function ( event ) {
    event.preventDefault();
    sendData();
  } );
} );

					

Here's the live result:

结论

Depending on the browser and the type of data you are dealing with, sending form data through JavaScript can be easy or difficult. The FormData object is generally the answer, and you can use a polyfill for it on legacy browsers.

另请参阅

Learning path

高级话题

发现此页面有问题吗?

最后修改: , 由 MDN 贡献者

  1. Complete beginners start here!
  2. Web 快速入门
    1. Getting started with the Web overview
    2. 安装基本软件
    3. What will your website look like?
    4. 处理文件
    5. HTML 基础
    6. CSS 基础
    7. JavaScript 基础
    8. 发布您的网站
    9. How the Web works
  3. HTML — Structuring the Web
  4. HTML 介绍
    1. Introduction to HTML overview
    2. Getting started with HTML
    3. What's in the head? Metadata in HTML
    4. HTML text fundamentals
    5. Creating hyperlinks
    6. Advanced text formatting
    7. Document and website structure
    8. Debugging HTML
    9. Assessment: Marking up a letter
    10. Assessment: Structuring a page of content
  5. 多媒体和嵌入
    1. Multimedia and embedding overview
    2. Images in HTML
    3. Video and audio content
    4. From object to iframe — other embedding technologies
    5. Adding vector graphics to the Web
    6. Responsive images
    7. Assessment: Mozilla splash page
  6. HTML 表格
    1. HTML tables overview
    2. HTML table basics
    3. HTML Table advanced features and accessibility
    4. Assessment: Structuring planet data
  7. CSS — Styling the Web
  8. CSS 第一步
    1. CSS first steps overview
    2. What is CSS?
    3. Getting started with CSS
    4. How CSS is structured
    5. How CSS works
    6. Using your new knowledge
  9. CSS 构建块
    1. CSS building blocks overview
    2. Cascade and inheritance
    3. CSS 选择器
    4. The box model
    5. Backgrounds and borders
    6. Handling different text directions
    7. Overflowing content
    8. Values and units
    9. Sizing items in CSS
    10. Images, media, and form elements
    11. Styling tables
    12. Debugging CSS
    13. Organizing your CSS
  10. 样式化文本
    1. Styling text overview
    2. Fundamental text and font styling
    3. Styling lists
    4. Styling links
    5. Web fonts
    6. Assessment: Typesetting a community school homepage
  11. CSS 布局
    1. CSS layout overview
    2. Introduction to CSS layout
    3. Normal Flow
    4. Flexbox
    5. Grids
    6. Floats
    7. 位置
    8. Multiple-column Layout
    9. Responsive design
    10. Beginner's guide to media queries
    11. Legacy Layout Methods
    12. Supporting Older Browsers
    13. Fundamental Layout Comprehension
  12. JavaScript — Dynamic client-side scripting
  13. JavaScript 第一步
    1. JavaScript first steps overview
    2. What is JavaScript?
    3. A first splash into JavaScript
    4. What went wrong? Troubleshooting JavaScript
    5. Storing the information you need — Variables
    6. Basic math in JavaScript — Numbers and operators
    7. Handling text — Strings in JavaScript
    8. Useful string methods
    9. 数组
    10. Assessment: Silly story generator
  14. JavaScript 构建块
    1. JavaScript building blocks overview
    2. Making decisions in your code — Conditionals
    3. Looping code
    4. Functions — Reusable blocks of code
    5. Build your own function
    6. Function return values
    7. 事件介绍
    8. Assessment: Image gallery
  15. 引入 JavaScript 对象
    1. Introducing JavaScript objects overview
    2. Object basics
    3. 对象原型
    4. Object-oriented programming concepts
    5. Classes in JavaScript
    6. Working with JSON data
    7. Object building practice
    8. Assessment: Adding features to our bouncing balls demo
  16. 异步 JavaScript
    1. Asynchronous JavaScript overview
    2. General asynchronous programming concepts
    3. Introducing asynchronous JavaScript
    4. Cooperative asynchronous Java​Script: Timeouts and intervals
    5. Graceful asynchronous programming with Promises
    6. Making asynchronous programming easier with async and await
    7. Choosing the right approach
  17. 客户端侧 Web API
    1. 客户端侧 Web API
    2. Introduction to web APIs
    3. Manipulating documents
    4. Fetching data from the server
    5. Third party APIs
    6. Drawing graphics
    7. Video and audio APIs
    8. Client-side storage
  18. Web forms — Working with user data
  19. Core forms learning pathway
    1. Web forms overview
    2. Your first form
    3. How to structure a web form
    4. Basic native form controls
    5. The HTML5 input types
    6. Other form controls
    7. Styling web forms
    8. Advanced form styling
    9. UI pseudo-classes
    10. Client-side form validation
    11. Sending form data
  20. Advanced forms articles
    1. How to build custom form controls
    2. Sending forms through JavaScript
    3. CSS property compatibility table for form controls
  21. Accessibility — Make the web usable by everyone
  22. Accessibility guides
    1. Accessibility overview
    2. What is accessibility?
    3. HTML: A good basis for accessibility
    4. CSS and JavaScript accessibility best practices
    5. WAI-ARIA basics
    6. Accessible multimedia
    7. Mobile accessibility
  23. Accessibility assessment
    1. Assessment: Accessibility troubleshooting
  24. Tools and testing
  25. Client-side web development tools
    1. Client-side web development tools index
    2. Client-side tooling overview
    3. Command line crash course
    4. Package management basics
    5. Introducing a complete toolchain
    6. Deploying our app
  26. Introduction to client-side frameworks
    1. Client-side frameworks overview
    2. Framework main features
  27. React
    1. Getting started with React
    2. Beginning our React todo list
    3. Componentizing our React app
    4. React interactivity: Events and state
    5. React interactivity: Editing, filtering, conditional rendering
    6. Accessibility in React
    7. React resources
  28. Ember
    1. Getting started with Ember
    2. Ember app structure and componentization
    3. Ember interactivity: Events, classes and state
    4. Ember Interactivity: Footer functionality, conditional rendering
    5. Routing in Ember
    6. Ember resources and troubleshooting
  29. Vue
    1. Getting started with Vue
    2. Creating our first Vue component
    3. Rendering a list of Vue components
    4. Adding a new todo form: Vue events, methods, and models
    5. Styling Vue components with CSS
    6. Using Vue computed properties
    7. Vue conditional rendering: editing existing todos
    8. Focus management with Vue refs
    9. Vue resources
  30. Svelte
    1. Getting started with Svelte
    2. Starting our Svelte Todo list app
    3. Dynamic behavior in Svelte: working with variables and props
    4. Componentizing our Svelte app
    5. Advanced Svelte: Reactivity, lifecycle, accessibility
    6. Working with Svelte stores
    7. TypeScript support in Svelte
    8. Deployment and next steps
  31. Angular
    1. Getting started with Angular
    2. Beginning our Angular todo list app
    3. Styling our Angular app
    4. Creating an item component
    5. Filtering our to-do items
    6. Building Angular applications and further resources
  32. Git and GitHub
    1. Git and GitHub overview
    2. Hello World
    3. Git Handbook
    4. Forking Projects
    5. About pull requests
    6. Mastering Issues
  33. Cross browser testing
    1. Cross browser testing overview
    2. Introduction to cross browser testing
    3. Strategies for carrying out testing
    4. Handling common HTML and CSS problems
    5. Handling common JavaScript problems
    6. Handling common accessibility problems
    7. Implementing feature detection
    8. Introduction to automated testing
    9. Setting up your own test automation environment
  34. Server-side website programming
  35. 第一步
    1. First steps overview
    2. Introduction to the server-side
    3. Client-Server overview
    4. Server-side web frameworks
    5. Website security
  36. Django Web 框架 (Python)
    1. Django web framework (Python) overview
    2. 介绍
    3. 设置开发环境
    4. Tutorial: The Local Library website
    5. Tutorial Part 2: Creating a skeleton website
    6. Tutorial Part 3: Using models
    7. Tutorial Part 4: Django admin site
    8. Tutorial Part 5: Creating our home page
    9. Tutorial Part 6: Generic list and detail views
    10. Tutorial Part 7: Sessions framework
    11. Tutorial Part 8: User authentication and permissions
    12. Tutorial Part 9: Working with forms
    13. Tutorial Part 10: Testing a Django web application
    14. Tutorial Part 11: Deploying Django to production
    15. Web application security
    16. Assessment: DIY mini blog
  37. Express Web Framework (node.js/JavaScript)
    1. Express Web Framework (Node.js/JavaScript) overview
    2. Express/Node introduction
    3. Setting up a Node (Express) development environment
    4. Express tutorial: The Local Library website
    5. Express Tutorial Part 2: Creating a skeleton website
    6. Express Tutorial Part 3: Using a database (with Mongoose)
    7. Express Tutorial Part 4: Routes and controllers
    8. Express Tutorial Part 5: Displaying library data
    9. Express Tutorial Part 6: Working with forms
    10. Express Tutorial Part 7: Deploying to production
  38. Further resources
  39. Common questions
    1. HTML questions
    2. CSS questions
    3. JavaScript questions
    4. Web mechanics
    5. Tools and setup
    6. Design and accessibility