How to send a JSON object using html form data How to send a JSON object using html form data json json

How to send a JSON object using html form data


Get complete form data as array and json stringify it.

var formData = JSON.stringify($("#myForm").serializeArray());

You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it using json_decode. You'll then get all data in an array.

$.ajax({  type: "POST",  url: "serverUrl",  data: formData,  success: function(){},  dataType: "json",  contentType : "application/json"});


HTML provides no way to generate JSON from form data.

If you really want to handle it from the client, then you would have to resort to using JavaScript to:

  1. gather your data from the form via DOM
  2. organise it in an object or array
  3. generate JSON with JSON.stringify
  4. POST it with XMLHttpRequest

You'd probably be better off sticking to application/x-www-form-urlencoded data and processing that on the server instead of JSON. Your form doesn't have any complicated hierarchy that would benefit from a JSON data structure.


Update in response to major rewrite of the question…

  • Your JS has no readystatechange handler, so you do nothing with the response
  • You trigger the JS when the submit button is clicked without cancelling the default behaviour. The browser will submit the form (in the regular way) as soon as the JS function is complete.


You can try something like:

<html><head>    <title>test</title></head><body>    <form id="formElem">        <input type="text" name="firstname" value="Karam">        <input type="text" name="lastname" value="Yousef">        <input type="submit">    </form>    <div id="decoded"></div>    <button id="encode">Encode</button>    <div id="encoded"></div></body><script>    encode.onclick = async (e) => {        let response = await fetch('http://localhost:8482/encode', {                method: 'GET',                headers: {                    'Content-Type': 'application/json',                },        })        let text = await response.text(); // read response body as text        data = JSON.parse(text);        document.querySelector("#encoded").innerHTML = text;      //  document.querySelector("#encoded").innerHTML = `First name = ${data.firstname} <br/>       //                                                  Last name = ${data.lastname} <br/>      //                                                  Age    = ${data.age}`    };    formElem.onsubmit = async (e) => {      e.preventDefault();      var form = document.querySelector("#formElem");     // var form = document.forms[0];        data = {          firstname : form.querySelector('input[name="firstname"]').value,          lastname : form.querySelector('input[name="lastname"]').value,          age : 5        }        let response = await fetch('http://localhost:8482/decode', {                method: 'POST', // or 'PUT'                headers: {                    'Content-Type': 'application/json',                },                body: JSON.stringify(data),        })        let text = await response.text(); // read response body as text        document.querySelector("#decoded").innerHTML = text;    };</script></html>