Potatosaurus Potatosaurus -4 years ago 105
HTML Question

How do I submit a JSON encoded post request from an HTML form?

Currently I'm trying to send a post request to a server I have, which is configured to only accept JSON data.

Unfortunately, when I inspect the post request through the developer console of my browser, it sends the data not encoded as JSON, but as an encoded url so the response is of type 415, due to the discrepancy between expected type and provided data.

The form:

<form action='http://myhost.elasticbeanstalk.com/API/Beta/Register' method = 'post' enctype='application/json'>
Email: *<br>
<input type='text' name='Email' style='width: 500px;' value='{"Email":"test@gmail.com"}'><br>
(Fields denoted with * are mandatory)
<input type='submit' value='Apply' style='float: right;'>

As you can see, I should in theory send a request of content type json, however if you examine the request that gets sent, you see that the content type remains as an encoded url, yet the tag "enctype='application/json'" should fix that unless I'm mistaken.

(imgur is currently down, as usual, so I'll change this image to a more permanent link when possible)


Am I missing something?

Answer Source

Browsers natively do not support JSON as a media type with HTML. Use XMLHttpRequest/Ajax to submit your form as JSON. Dummy example using jQuery:

          url: 'http://yoururl',
          type: 'POST',
          data: yourFormDataSearilized
          contentType: 'application/json', // this is what you want
          success: function() {
            // check
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download