Larry Larry - 6 months ago 38
Javascript Question

Formulate JSON in JavaScript from HTML form textarea values and Post?

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.

Answer

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>