0

I'm trying to use javascript to generate a form that will post to a webservice. However, I've been having trouble formatting my data correctly. It needs to be in json? How would I go about making this form.

var form = document.createElement('form');
with (form) {
    setAttribute("name", "theForm"); // give form a name
    setAttribute("action", pathTOGO); // give form an action
    setAttribute("method", "post"); // give form a method

}


document.getElementsByTagName("body")[0].appendChild(form);
document.forms[0].submit();

However, the pathTOGO needs the post to include information in json format. How do I use javascript to specify that this form will send

{
   "Auth": "",
   "User":"",

}

where the strings are filled in as well as ensure the to post knows

Content-Type = application/json

Any help is much appreciated. Basically what im askingis how do I create a form that make this exact HTTP post using javascript?

POST /WEBSITEPOSTLOCATION HTTP/1.1
Host: WEBSITE
Content-Type: application/json

{
    "Auth":"SOMEVAL",
    "User":"SOMENAME"
}

Thank you so much.

Stevie
  • 89
  • 8

1 Answers1

0

Form post data to the server as name=value, so in order to do it with a form you need to post the JSON object stringified on a parameter. For example you can put an input (type="text") inside your form with the name json and for value the JSON object (inputelement.value=JSON.stringify(myJsonObject)). The server will then get the a parameter with the name json with the json text.

But you should use ajax request to post your data easier, even if you call it from a button.

Here is a similar question : How to send a JSON object using html form data

Community
  • 1
  • 1
GramThanos
  • 3,572
  • 1
  • 22
  • 34