GithubHelp home page GithubHelp logo

brainfoolong / form-data-json Goto Github PK

View Code? Open in Web Editor NEW
56.0 7.0 10.0 333 KB

A zero dependency, cross browser library to easily get or set/manipulate form input values as/from a json object.

Home Page: https://brainfoolong.github.io/form-data-json

License: MIT License

JavaScript 100.00%
javascript forms json inputfield converter select serializejson formdata cross-browser form form-validation

form-data-json's Introduction

Form Data Json Logo

Form Data Json - Form input values to/from JSON (And a bit more...)

A zero dependency, cross browser library to easily get or set/manipulate form input values as/from a json object. It can handle all input types, including multidimensional array names and file input. Native FormData is limited to reading only, we have way more:

  • Read data as multidimensional object or as a flat list (similar to FormData)
  • Write data into forms
  • Read unchecked/disabled fields as well
  • Read file inputs as base64, arraybuffer, etc...
  • Clear forms
  • Reset forms to their defaults
  • And, you don't even need a <form> element, we accept every container, even the <body>
  • Super small: ~3kB gzipped
  • Cross Browser including IE11 (Yes, the ugly one also)

Installation

Download latest release and include dist/form-data-json.min.js into your project.

<script src="dist/form-data-json.min.js"></script>
CDN (Latest version automatically, do not use it in production because of possible breaking changes)
<script src="https://cdn.jsdelivr.net/npm/form-data-json-convert/dist/form-data-json.min.js"></script>
NPM
npm install form-data-json-convert
// import in NodeJS: const FormDataJson = require('form-data-json-convert')
ES6 Module
import FormDataJson from 'pathtodistfolder/form-data-json.es6.js'

What's not supported

  • Write to <input type="file"> It's impossible in javascript to set values for file inputs, for security reasons. However, reading file input as base64 data uri string is supported.

How to use

Read data

let values = FormDataJson.toJson(document.querySelector("form")) // with native element
let values = FormDataJson.toJson("#form-id") // with selector
let values = FormDataJson.toJson($("#form-id")) // with jQuery
Read form input values as a flat object (similar to native FormData())
let values = FormDataJson.toJson(document.querySelector("form"), { flatList: true })
Read form input values including disabled
let values = FormDataJson.toJson(document.querySelector("form"), { includeDisabled: true })
Read with file inputs as base64 data uri
FormDataJson.toJson(document.querySelector("form"), {
  filesCallback: function (values) {
    console.log(values)
  }
})
Read form input values but filter out, for example, all password fields
let values = FormDataJson.toJson(document.querySelector("form"), {
  inputFilter: function (inputElement) {
    return (inputElement.type || 'text') !== 'password'
  }
})

Write data

FormDataJson.fromJson(document.querySelector("form"), { 'name': 'BrainFooLong' })
Set form input values and clear all other existing input values
FormDataJson.fromJson(document.querySelector("form"), { 'name': 'BrainFooLong' }, { clearOthers: true })
Reset all input fields to their default values
FormDataJson.reset(document.querySelector("form"))
Clear all input fields to empty values
FormDataJson.clear(document.querySelector("form"))
All default options for toJson()

You can edit this defaults globally by modifying FormDataJson.defaultOptionsToJson.

{
/**
 * Include all disabled field values
 * @type {boolean}
 */
'includeDisabled': false,

/**
 * Include all button field values
 * @type {boolean}
 */
'includeButtonValues': false,

/**
 * Include all unchecked radio/checkboxes as given value when they are unchecked
 * If undefined, than the unchecked field will be ignored in output
 * @type {*}
 */
'uncheckedValue': undefined,

/**
 * A function, where first parameter is the input field to check for
 * Must return true if the field should be included
 * All other return values, as well as no return value, will skip the input field in the progress
 * @type {function|null}
 */
'inputFilter': null,

/**
 * Does return an array list, with same values as native Array.from(new FormData(form))
 * A list will look like [["inputName", "inputValue"], ["inputName", "inputValue"]]
 * The input name will not be changed and the list can contain multiple equal names
 * @type {boolean}
 */
'flatList': false,

/**
 * If true, then this does skip empty fields from the output
 * Empty is considered to be:
 * An empty array (for multiple selects/checkboxes)
 * An empty input field (length = 0 or null)
 * This does recursively remove keys
 * Example: {"agb":"1", "user" : [{"name" : ""},{"name" : ""}]} will be {"agb":"1"}
 * @type {boolean}
 */
'skipEmpty': false,

/**
 * A function that will be called when all file fields are read as base64 data uri
 * First passed parameter to this function are the form values including all file data
 * Note: If set, the original return value from toJson() returns null
 * @type {function|null}
 */
'filesCallback': null,

/**
 * By default, files are read as base64 data url
 * Possible values are: readAsDataURL, readAsBinaryString, readAsText, readAsArrayBuffer
 * @type {string}
 */
'fileReaderFunction': 'readAsDataURL',

/**
 * If true than values try to be a real Array instead of Object where possible
 * If false than all values that are multiple (multiple select, same input names checkboxes, unnamed array indexes, etc...) will be objects
 * @type {boolean}
 */
'arrayify': true
}
All default options for fromJson()

You can edit this defaults globally by modifying FormDataJson.defaultOptionsFromJson.

{
/**
 * Does expect the given values are in a flatList, previously exported with toJson
 * Instead of the default bevhiour with nested objects
 * @type {boolean}
 */
'flatList': false,

/**
 * If true, than all fields that are not exist in the passed values object, will be cleared/emptied
 * Not exist means, the value must be undefined
 * @type {boolean}
 */
'clearOthers': false,

/**
 * If true, than all fields that are not exist in the passed values object, will be reset
 * Not exist means, the value must be undefined
 * @type {boolean}
 */
'resetOthers': false,

/**
 * If true, when a fields value has changed, a "change" event will be fired
 * @type {boolean}
 */
'triggerChangeEvent': false
}

How to contribute

  • Please write an issue before you start programming.
  • Always test the official supported browsers.
  • Write all tests in docs/tests/test.html. Each new option must have an own test.

form-data-json's People

Contributors

brainfoolong avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

form-data-json's Issues

Automatic array processing while fromJson

Hi!
I`v got a form and get a data from DB for It. The data has the same structure:

{
  Company: [
    {
      id: 2,
      name: 'PanamaServ',
      Address: [
        {
          Country: [
            {
              id: 2,
              name: 'USA',
            },
          ],
          address: 'Porkold 11a',
          city: 'NewYork',
          company_id: 2,
          country_id: 2,
          id: 4,
          post_code: 34246,
          region:'ZP',
        },
      ],
      Email: [
        {
          company_id: 2,
          email: '[email protected]',
          id: 3,
        },
        {
          company_id: 2,
          email: '[email protected]',
          id: 2,
        },
      ],
    },
  ],
}

It is necessary to use array because the DB can returns multiple objects. So therefore I should use corresponding names for input fields of the form:

name="Company[0][Address][0][country_id]"
name="Company[0][Email][0][email]"

It is inconvenient to get first element always.

It would be great the fromJson method automatically get first element of an array. And returns callback to process the array in custom function and logging to the console to inform a user if the array has multiple elements.
I think it might looks like:

function process_array ( array ) {
    return array[2];
}

It Probably needs an option for this behavior.

Typing of typescript Suggestion

First, congratz of your job.

I use with typescript and want suggest a little help to other people

declare module 'form-data-json-convert' {
	interface OptionsToJson {
	  includeDisabled?: boolean;
	  includeButtonValues?: boolean;
	  uncheckedValue?: any;
	  inputFilter?: ((inputElement: HTMLInputElement) => boolean) | null;
	  flatList?: boolean;
	  skipEmpty?: boolean;
	  filesCallback?: ((values: any) => void) | null;
	  fileReaderFunction?: string;
	  arrayify?: boolean;
	}
  
	interface OptionsFromJson {
	  flatList?: boolean;
	  clearOthers?: boolean;
	  resetOthers?: boolean;
	  triggerChangeEvent?: boolean;
	}
  
	function toJson(
	  form: HTMLFormElement | string | JQuery,
	  options?: OptionsToJson
	): any;
  
	function fromJson(
	  form: HTMLFormElement | string | JQuery,
	  values: any,
	  options?: OptionsFromJson
	): void;
  
	function reset(form: HTMLFormElement | string | JQuery): void;
  
	function clear(form: HTMLFormElement | string | JQuery): void;
  
	const defaultOptionsToJson: OptionsToJson;
	const defaultOptionsFromJson: OptionsFromJson;
  }

v2-dev: toJson return object instead of array:

Describe the bug

	<input name = "client[][phone][]">
	<input name = "client[][phone][]">
	<input name = "client[][phone][]">


	<input name = "client[][email][]">
	<input name = "client[][email][]">


	<input name = "client[][phone][]">
	<input name = "client[][phone][]">

	<input name = "client[][email][]">
	<input name = "client[][email][]">
	<input name = "client[][email][]">

To Reproduce

FormDataJson.toJson( $('form') )

image

Here I get 10 array elements as expected (green),
also first phone is pushed into array as expected, but next phone (second, third) are objects
first email is array as expected, but next email (second) is object

for second,third email/phone I expect arrays

**probably this example is meaningless, because this is unusual to create email, phone objects at separate array elements. They should be grouped together semantically. So for this case warning should be issued.

**despite on unusual naming objects are not expected, e.g. counter should be flushed, when [] is processing
To my mind it should be just command to push into array and counter should not have matter. For cases when it has matter developer will use explicit value: [1] or [7] etc. (see post below)

Module parse failed: Unexpected token (15:30)

Describe the bug

Message:
    ./src/js/common/form-data-json.cjs 15:30
Module parse failed: Unexpected token (15:30)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|    * @type {{}}
|    */
>   static defaultOptionsToJson = {
|     /**
|      * Include all disabled field values
 @ ./src/js/common/form-data-json-exposed.cjs 1:33-66
 @ ./src/js/modal.js
Details:
    domainEmitter: [object Object]
    domainThrown: false

To Reproduce
Unknown. Just upgraded from 2.1.3 to 2.1.4

Probably there is problem with my tooling, but there is no any notices about requirements at changelog.

FR: It seems excess to do `new FormDataJsonOptions`

It seems too verbose to write each time: new FormDataJsonOptions.
To pass values we could just pass a simple hash. If this is required by code then this hash could be turned into FormDataJsonOptions internally

also these methods fillFormFromJsonValues, formToJson could be simplified to: fillForm, readForm
or toForm, toJson. Is there any reason for long typing?

unsetAllInputsOnFill -> clearForm.
+implement resetForm. Different is that clearForm - clears all inputs, resetForm set default form values if there is not corresponding value at supplied hash.

Thank you

Name syntax with dot

Hi! Now to specify nesting I have to use '[ ]' in field name.

Maybe It would be more convenient to use '.'
Example (something like this):

<input name="Company[Phone][0][phone]" type="text" value="34343">
<input name="Company.Phone[0]phone" type="text" value="34343">

Where the data is:

{
 Company: {
  Phone: [{
     phone: 34343,
   }],
 },
}

Manipulating defaults for FormDataJsonOptions

Make defaults possible to edit by code.

Adding a static property defaults with key/value pair instead of pre-filled property values should do the trick. So the user can edit the defaults property to their needs.

Trigger for 'onchange'

Is your feature request related to a problem? Please describe.
Hey! I am using the 'fromJson' method to set data to my form. And I have disabled fields. Fields filled by the 'onchange' event on some other fields. But when filling out the form with 'fromJson', 'onchange' doesn't fire.

Describe the solution you'd like
It would be usefull triger 'onchange' when we set data to Form programmatically.
In support of the popularity of this need, I provide a link:
https://stackoverflow.com/questions/3179385/val-doesnt-trigger-change-in-jquery

v2-dev: make `uncheckedValue` false by default

Is your feature request related to a problem? Please describe.

	<input type="checkbox" name="scales[]">
	<input type="checkbox" name="scales[]" value="77">

image

Describe the solution you'd like
If uncheckedValue is undefined by default then result of .toJson can not be passed .fromJson
eg. operation is not reversable

At this example we have two check boxes. Second have value 77. And when we setup { scales: ['77'] } nothing is selected, because first checkbox does not have 77 value.

So in this case we need to loop over all checkboxes with scales names to work properly.
Even doing so, we have corner case:

	<input type="checkbox" name="scales[]">
	<input type="checkbox" name="scales[]">
	<input type="checkbox" name="scales[]" value="77">

When second scales is checked result will be { scales: [ 'on' ] }. And we will not know which was checked: first or second??

So for consistent results and for reverse (result of .toJson can be passed back .fromJson (so backend can send data as is)): please make uncheckedValue false by default

Thank you

Elements out of order are processed incorrectly

HI! I`v got a little bit problem. When my input fields have names (index) out of order the hash is in wrong format.

<input type="hidden" name="Company[Phone][0][id]"         value="122"                   class="form-control" />
<input type="hidden" name="Company[Phone][0][phone]"  value="3339991111"     class="form-control" />

<input type="hidden" name="Company[Phone][2][id]"         value="125"                   class="form-control" />
<input type="hidden" name="Company[Phone][2][phone]"  value="33"                    class="form-control" />

Phone => {
      0 => {
        id => 122,
        phone => 3339991111,
      },
      2 => {
        id => 125,
        phone => 33,
      },

I dynamically add and delete fields so the situation is common. Maybe there is sense to use array without index (like additional opportunity to use the array). For method 'fromJson' use each next element without index binding.

<input type="hidden" name="Company[Phone][][id]"         value="122"                   class="form-control" />
<input type="hidden" name="Company[Phone][][phone]"  value="3339991111"     class="form-control" />

Add Input file read

  • Test added in tests/test.html
  • Updated minified version with npm run dist
  • Updated Changelog.md
  • Updated version in package.json
  • Created a new release
  • Published new NPM package with npm publish

radio element value 0

Hi

First of all thanks for plugin

I am not filling radio element if its value is 0. ()
if I convert to string or bigger then 0 it is ok.
ex : { opened : 0 } not running

Implement FormDataGraphQL

Is your feature request related to a problem? Please describe.
Hi. We have complex forms. For example Company have multiple emails, phones. While we can send this at object like:

{ Company => { name => 'x', phones => [{ phone => '1234' },{ phone => '12345' }], emails => [{...},{...}] } }

We want to do same thing via GraphQL

It would be nice if FormDataJson will be able to send this data at GraphQL format

Describe the solution you'd like
https://graphql.org/

Get empty value in the data if use field name with nesting (array)

Hi! I suppose I do not understand something.
I need data in format:

{
   _Company: {
      name: 'xxx',
      _Phone: [
        {
            phone: 3333,
        }
     ],
  },
}

The 'skipEmpty' is on 'true'.
When I used the code without nesting array the empty value (id) was not presented in data:
<input type="hidden" name="_Company[_Phone][id]" class="form-control" />

Now I use
<input type="hidden" name="_Company[_Phone][0][id]" class="form-control" />
and data has id: , with empty value. Why is that?

Adding FormDataJsonOptions.defaults

Feature Request: #5

  • Test added in docs/tests/test.html
  • Updated minified version with npm run dist
  • Updated Changelog.md
  • Updated version in package.json
  • Created a new release
  • Published new NPM package with npm publish

Array is expected

Describe the bug
I expect array for multiple values, but hash is returned

To Reproduce

<form>
	<input name = "docn">
	<input name = "docdate">

	<input name = "client[name]">
	<input name = "client[edrpou]">

	<input name = "client[phone][]">
	<input name = "client[phone][]">
	<input name = "client[phone][]">


	<input name = "client[email][]">
	<input name = "client[email][]">

	<select name="client[status][]" id="cars" multiple>
	  <option value="volvo">Volvo</option>
	  <option value="saab">Saab</option>
	  <option value="opel">Opel</option>
	  <option value="audi">Audi</option>
	</select>

	<input type="checkbox" name="scales[]" checked value="77">
	<input type="checkbox" name="scales[]">
</form>
FormDataJson.fillFormFromJsonValues($("form")[0], 
  {docn : 'asdf', docdate: 'addd', client: { name: 'asdf DDD', phone: [ 'zzzz', 'dd' ] } }, 
  new FormDataJsonOptions({ unsetAllInputsOnFill: true }) 
)

image

v2-dev: implement `resetOthers` similar to .reset/.clear methods

Is your feature request related to a problem? Please describe.
We have clear, reset methods:

FormDataJson.reset(document.querySelector("form"))
FormDataJson.clear(document.querySelector("form"))

But only one option: clearOthers

Describe the solution you'd like
Impelement resetOthers option for usage with FormDataJson.fromJson( ... )

Doesn't work when inputs are nested more than one child element deep

Is your feature request related to a problem? Please describe.
Hi, I know this is probably a rare problem and I can find a workaround if needed, but I was wondering if there is a way for the library to work with forms who's inputs aren't the direct children of the form element. For example, I have a situation where each form is a table row, with each input in a cell across like so:

<tr>
        <form id="example">
          <td>
              <input type='text' name='firstName' class="inputLine" placeholder="First Name"></input>
          </td>
          <td>
              <input type='text' name='lastName' class="inputLine" placeholder="Last Name"></input>
          </td>
          <td>
              <input type='email' name='email' class="inputLine" placeholder="Email"></input>
          </td>
        </form>
      </tr>

If I try use this form in the library, it does not pull the input values. I am assuming that this is because the library looks for inputs that are only the direct children of the form. Is there a way to make this work somehow? If not, will it work if I use divs instead of TD's?

Describe the solution you'd like
Maybe a parameter on the function to specify how many nested in the inputs are.

v2-dev: `skipEmpty` still includes empty arrays/objects

Describe the bug
When nested form fields are not filled, they are included anyway

To Reproduce

	<input name = "client[name]">
	<input name = "client[edrpou]">

	<input name = "client[person][0][phone][]">
	<input name = "client[person][0][phone][]">
	<input name = "client[person][0][phone][]">


	<input name = "client[person][0][email][]">
	<input name = "client[person][0][email][]">


	<input name = "client[person][1][phone][]">
	<input name = "client[person][1][phone][]">

	<input name = "client[person][1][email][]">
	<input name = "client[person][1][email][]">
	<input name = "client[person][1][email][]">
	<select name="client[status][]" id="cars" multiple>
	  <option value="volvo">Volvo</option>
	  <option value="saab">Saab</option>
	  <option value="opel">Opel</option>
	  <option value="audi">Audi</option>
	</select>

	<input type="checkbox" name="scales[]">
	<input type="checkbox" name="scales[]" checked value="77">

image

Use `import` instead of `require`

Is your feature request related to a problem? Please describe.

import { FormDataJson as FormDataJson } from "form-data-json-convert/dist/form-data-json";

After this line of code FormDataJson stays undefined. Is this supported?

Describe the solution you'd like
Support modern way of module loading.

Selection of checkboxes should based on values instead of order in DOM

Describe the bug
When filling the form with data using FormDataJson.fromJson .... for checkboxes the checkbox is only selected if the data provided is the exact order that checkboxes appear in the DOM

To Reproduce
In the following example https://jsfiddle.net/yusafme/vuj3kth5/3/ the checkboxes are checked as you would expect

<form>
  Email<input name="communication[preference][]" type="checkbox" value="email">
  SMS<input name="communication[preference][]" type="checkbox" value="sms">
  Letter<input name="communication[preference][]" type="checkbox" value="letter">
</form>
<script>
let form = document.querySelector("form")
FormDataJson.fromJson(form, {communication:{
	preference:["email", "sms"]
}});
</script>

However in this example https://jsfiddle.net/yusafme/vuj3kth5/4/ only the first checkbox is checked, but you would want both the email checkbox and letter checkbox to be checked

<form>
  Email<input name="communication[preference][]" type="checkbox" value="email">
  SMS<input name="communication[preference][]" type="checkbox" value="sms">
  Letter<input name="communication[preference][]" type="checkbox" value="letter">
</form>
<script>
let form = document.querySelector("form")
FormDataJson.fromJson(form, {communication:{
	preference:["email", "letter"]
}});
</script>

Proposal to Improve the Manipulation of Masked Field Values in Forms

It would be good to have a way to manipulate the value of the field, for example, fields that use masks (like currency) are bringing the complete string "USD$ 100.32".

Just as we have the filterInput function, there could be something that iterates between the fields and allows us to manipulate the field's return; it would give much more flexibility to the developer.

This way, I could take the field that has the mask and process the value to return it as a number "100.32".

setInputValue on checkboxes that have initial value false to true doesn't work.

Describe the bug
FormDataJson.setInputValue() seems to work like this in the case of checkboxes:

inputElement.checked = value === inputElement.value

So, if the initial value is false, then true === false would return false.

Expected behaviour

FormDataJson.setInputValue(input, true); should set the input value to true.

Actual behaviour

FormDataJson.setInputValue(input, true); sets the input value to false.

To Reproduce
https://codepen.io/schart/pen/gOaYOGQ

Proposed fix

Changing line 57 from

inputElement.checked = value === inputElement.value

to

inputElement.checked = value


Is this here on purpose, or is it a bug?

how to skip non selected select option

I am using FormDataJson.toJson("#searchForm", {skipEmpty: true}), but I found that for select option:

<select name="gender">
	<option value="" selected></option>
	<option value="0" >Male</option>
	<option value="1" >Female</option>
</select>

if there is no valid option selected(that is Male or Female in this case), FormDataJson.toJson("#searchForm", {skipEmpty: true}) still return gender with null, what I suppose is to skip gender. I tried to change <option value="" selected></option> to <option ></option>, still not work.

how can I skip non selected select element?

Can not setup values to form

Describe the bug
this does not setup all form values, just client.name:

FormDataJson.fillFormFromJsonValues($("form")[0], {docn : 'asdf', docdate: 'addd', client: { name: 'asdf DDD'  } },
    new FormDataJsonOptions({ unsetAllInputsOnFill: true }) 
)

But this setup correct:

FormDataJson.fillFormFromJsonValues($("form")[0], {docn : 'asdf', docdate: 'addd', client: { name: 'asdf DDD'  } } ) 
)

To mine mind problem is when we go into nested data, then it clear outer form fields

Ignore hidden fields

Is your feature request related to a problem? Please describe.
I'm using this library to store form data into localStorage as a "draft". But I don't want to store hidden fields, because I don't want to store passwords, nor csrf tokens.

Describe the solution you'd like
I would be able to add an option in formToJson method to don't get hidden fields in json result, like something like:

let values = FormDataJson.formToJson(document.querySelector("form"), new FormDataJsonOptions({ includeHidden: false }))

I guess the default value for includeHidden should be true in order to prevent BC break, and to keep the same behaviour for those who want to POST the json to a server, and need the hidden fields.

By the way, thanks for this vanillaJs library, which is not dependant to jquery, or is not a react/angular module !

Conversion of a list of element[number] not done when a number is missing

Conversion of a list of element[number] not done when a number is missing
When the form contains inputs (e.g.) that want to become arrays in Json and these elements are not numbered properly (e.g. the bug happens if the element looks like this (see below) or contains no [0]).
Example :

input type="text" name="localisation[elementRoute][3][nom]" value="1945–1986" />
input type="text" name="localisation[elementRoute][3][nombre]" value="1945–1986" />

input type="text" name="localisation[elementRoute][2][nom]" value="1945–1986" />
input type="text" name="localisation[elementRoute][2][nombre]" value="1945–1986" />

input type="text" name="localisation[elementRoute][11][nom]" value="1945–1986" />
input type="text" name="localisation[elementRoute][11][nombre]" value="1945–1986" />

The result look like this :

{"localisation":{"elementRoute":{"3":{"nom":"1945–1986","nombre":"1945–1986"},"3":{"nom":"1945–1986","nombre":"1945–1986"},"2":{"nom":"1945–1986","nombre":"1945–1986"},"11":{"nom":"1945–1986","nombre":"1945–1986"}}

The result that 'I would like (or normally need to be) :

{"localisation":{"elementRoute":[{{"nom":"1945–1986","nombre":"1945–1986"},{"nom":"1945–1986","nombre":"1945–1986"},{"nom":"1945–1986","nombre":"1945–1986"}}]

It will be great if the "bug" will be fixed for less code (and more 'real' coding =) ).
Have a great day

Document how to import this module

I download form-data-json.js into my package and try to import this module:

const FormDataJson = require('../common/form-data-json.js');

export function ajaxForm(form) {
  const formData  = FormDataJson.toJson( form );

But get error: FormDataJson is not defined

How to import this module?

NPM Module?

Describe the bug
There's an npm install in the readme but can not import?

To Reproduce

import FormDataJson from "form-data-json-convert"
const FormDataJson2 = require("form-data-json-convert")

// both returns empty objects

Wouldn't it be nicer if toJSON returns promise

When converting form it could be take time to convert file fields. I think it would be better if toJson returns a promise so we can be sure that it worked 100% as we use it with toJson().then()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.