2

I must be making a very stupid mistake, but I can't figure out why this isn't working:

<html>
    <head>
        <title>Form test</title>
    </head>
    <body>
        <h1>Test a form</h1>
        <form id="myform" name="myform" action="/server">
            <input type="text" name="username" value="johndoe">
            <input type="number" name="id" value="123456">
            <input type="submit" onclick="return sendForm(this.form);">
        </form>

        <script>

            function sendForm(form) {
                var formData = new FormData(form);
                console.log("as json: " + JSON.stringify(formData));
                return false; // Prevent page from submitting.
            }
        </script>

    </body>
</html>

According to the documentation of FormData, if you give it a form object in the constructor, it will populate itself with the form values, but when I do this, I get an empty result in the console. Any ideas what I'm doing wrong in this? I tried in both Chrome and Firefox and got the same results. This is based on the example from html5rocks XHR2.

Thank you

user2959589
  • 362
  • 1
  • 9
  • 23

2 Answers2

0

You are doing nothing wrong here. You need to use the methods like .entires(), .get(), .getAll() and so on to access the values, or keys. I had the same issue some time ago, and if you need to convert your FormData to JSON, you need to write some code, which does this for you, JSON.stringify() does not work in this case. Have a look here

Or, if you need a jQuery solution: SO

Community
  • 1
  • 1
philipp
  • 15,947
  • 15
  • 61
  • 106
0

I figured out what I need to do. It's simple:

console.log("Here it is: " + JSON.stringify($('#myform').serializeArray()[0]));

Gives the expected result: a JSON string containing name / value pairs from the form. I can then send this using XMLHttpRequest. No reason to use a FormData object in this case.

user2959589
  • 362
  • 1
  • 9
  • 23