2

I want to have an HTML form that posts the following in an Http-request body.

{ “info” : {
     “id” : “123”
     “text1” : <comes from html text-box>
}

So, what I want is to formulate the above as a JavaScript Object, and then post this JavaScript object on submit. The value of “text1” will be coming from user input, that will be an html-form textarea input box. The first value “id” will be hard-coded, or could also come from a hidden text-box.

So my question is: how can I write a piece of JavaScript to achieve this, together with the corresponding html form, etc.

3 Answers 3

2

It is easiest to do this using jQuery.

First, initialize a JavaScript object with your data. Then, use jQuery to extract the text from the text box and assign it to the desired property in your object.

var data = { 
    "info": {
        "id":"123",
        "text1":"" 
    }
};

data.info.text1 = $("#yourTextBox").val();

Then you can use jQuery.ajax to make the request:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

See the jQuery documentation for posts: http://api.jquery.com/jQuery.post/

EDIT: Using inline javascript, your HTML would look something like this (not using jQuery to grab the form data):

<html>
<head>
<script>
var data = { 
    "info": {
        "id":"123",
        "text1":"" 
    }
};
function makeRequest()
{
    data.info.text1 = document.forms["frm1"]["fname"].value;

    $.ajax({
        type: "POST",
        url: url,
        data: data,
        success: success,
        dataType: dataType
    });
}
</script>
</head>
<body>

<form name="frm1" id="yourTextBox" onsubmit="makeRequest()">
<input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks very much for your reply, although how exactly do I call the ajax function on my form submit (perhaps you could add this code for sake of completion of this question).
I updated the code based on the assumption that you are using inline javascript. Let me know if there is anything you'd like to see differently.
2
<html>
 <head>
  <script>
   function sendJson()
   {
   var x=document.forms["alfa"]["text1"].value;
   str1="{ 'info' : { 'id' : '123' 'text1' : ";
   str2=str1.concat(x);
   body=str2.concat(" }");
   document.forms["alfa"]["text1"].value=body;
   }
  </script>
 </head>
 <body>
  <form id="alfa" onsubmit="return sendJson()">
   Text1: <input id="text1" type=text size=50>
   <input type="submit" value="Submit">
  </form>
 </body>
</html>

Comments

0

The best way is to use JSON.parse()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.