2

I created a JSP page with few input fields. When i click on submin, i need the javascript to create json object and put input values in it and i want to display the json data in same jsp page.

This is my form

<form name="jsond" method="get">
<br>
<p id="msg"></p>
First Name:
<input type="text" id="firstName"/><br>
Last Name:
<input type="text" id="lastName"/><br>
E-mail:
<input type="text" id="email"/><br>
Mobile No:
<input type="text" id="mobile"/><br>
Place:
<input type="text" id="place"/><br>
Country:
<input type="text" id="country"/><br>
<br>
<input type="submit" name="submit" value="Submit" onclick="return submitForm(this, event);">
</form>

And this is my script

function submitForm(thisObj, thisEvent) {
       var firstName = document.forms["jssond"]["firstName"].value;
       var lastName = document.forms["jssond"]["lastName"].value;
       var email = document.forms["jssond"]["email"].value;
       var mobile = document.forms["jssond"]["mobile"].value;
       var place = document.forms["jssond"]["place"].value;
       var country = document.forms["jssond"]["country"].value;

// How to do the remaining code? I want to store the above variables in json object and display json values in <p id="msg"></p>

How to pass the json object to servlet from javascript?

Thanks

  • Are you sure you want to create JSON or just a JavaScript object? Have a look at the MDN guide to learn about objects: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects. – Felix Kling Mar 13 '13 at 08:13
  • i want to create JSON, not javascript variable –  Mar 13 '13 at 08:15
  • *related*: http://stackoverflow.com/questions/4162749/convert-js-object-to-json-string – Felix Kling Mar 13 '13 at 08:24
  • Your approach does not make sense. JSP means *JavaServer* Pages. Java != JavaScript. – PointedEars Mar 13 '13 at 08:34

3 Answers3

3

You can create object in javascript and then use JSON.stringify to create JSON as text.

function submitForm(thisObj, thisEvent) {
   var object = {
       firstName: document.forms["jssond"]["firstName"].value,
       lastName: document.forms["jssond"]["lastName"].value,
       email: document.forms["jssond"]["email"].value,
       mobile: document.forms["jssond"]["mobile"].value,
       place: document.forms["jssond"]["place"].value,
       country: document.forms["jssond"]["country"].value
   };
   document.getElementById('msg').innerHTML = JSON.stringify(object);
}
jcubic
  • 61,973
  • 54
  • 229
  • 402
2

Well JSON is very similar to JavaScript object with key-value pairs, it's simpler than you think :)

// retrieve the form values
var firstName = document.forms["jssond"]["firstName"].value;
var lastName = document.forms["jssond"]["lastName"].value;
var email = document.forms["jssond"]["email"].value;
var mobile = document.forms["jssond"]["mobile"].value;
var place = document.forms["jssond"]["place"].value;
var country = document.forms["jssond"]["country"].value;

// create JSON
var jsonObj = {
    "firstname": firstName,
    "lastName": lastName,
    "email": email,
    "mobile": mobile,
    "place": place,
    "country": country
};
// convert JSON to string
var jsonString = JSON.stringify(jsonObj);

Submitting the JSON in form:

To submit the JSON data in the form submit:

Say you have a hidden field in the form that you'll use for holding the JSON string value:

<input type=hidden" id="jsonData" name="jsonData" />

After you created the jsonString, you can put the JSON string value into the hidden form element:

document.getElementById('jsonData').value = jsonString;

Handling the JSON server-side:

And in your server-side code that's handling the form submit action, say in PHP (there's probably something equivalent in whatever language you're using):

<?php
    $jsonObject = json_decode($_POST['jsonData'], true);
?>

So $jsonObject is now an associate array in this format:

[
    "firstName" => "...",
    "lastName" => "...",
    "email" => "...",
    "mobile" => "...",
    "place" => "...",
    "country" => "..." 
]

In Java:

// Assuming 'request' is HttpServletRequest

String jsonString = request.getParameter("jsonData");
JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonString);
Amy
  • 7,388
  • 2
  • 20
  • 31
  • 2
    No, JSON **is not** a JavaScript object. JSON is a **textual** data representation, just like XML. To create JSON from an object, you have to call `JSON.stringify`. It's a common mistake to refer to JavaScript object/array literals as JSON, but this is wrong and confusing, especially for beginners. – Felix Kling Mar 13 '13 at 08:12
  • @FelixKling JSON format is based on JavaScript. I'm not literally saying that JSON is an object in JavaScript. I'm merely saying that the representation of the two is pretty much the same. In the context of this question, `JSON.stringify` would be the next step if we want to represent the JSON as a string. Which would be `{"firstname": firstName,"lastName": lastName,"email": email,"mobile": mobile,"place": place,"country": country}` (but with actual values in place of the variable names). But he didn't specify how he wanted to output the JSON, so it's up to him how we wants to represent it. – Amy Mar 13 '13 at 08:18
  • Yes, the syntax is similar but that does not mean one can use the terminology interchangeably. And actually, you *did* say *"Well JSON is just an JavaScript object with key-value pairs"*. Your `jsonObj` is not JSON [nor a JSON object](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/), it's simply an object. And JSON can **only** exist as a string in JavaScript. – Felix Kling Mar 13 '13 at 08:22
  • @sweetamylase i want to represent JSON as string –  Mar 13 '13 at 08:22
  • JSON is a *data format* similar to and compatible with the notation used for ECMAScript `Object` initializers. It is a structured string of characters that can be *parsed into* an ECMAScript object (the opposite is not the case). The only "JSON object" is the (now built-in) one that does the parsing and generation of JSON content. – PointedEars Mar 13 '13 at 08:27
  • I understand your point @FelixKling sorry if I caused any confusion. Let's not diverge from the issue at hand, which is answering Shiju's question :) I've updated the answer. – Amy Mar 13 '13 at 08:29
  • I dont know i can answer here or not. I want to pass that JSON object _jsonString_ to the servlet in form action. How to do that? –  Mar 13 '13 at 09:42
  • @ShijuKBabu I've updated the answer with how you may handle the JSON object server-side. – Amy Mar 13 '13 at 14:16
1
function submitForm(thisObj, thisEvent) {
   var firstName = document.forms["jssond"]["firstName"].value;
   var lastName = document.forms["jssond"]["lastName"].value;
   var email = document.forms["jssond"]["email"].value;
   var mobile = document.forms["jssond"]["mobile"].value;
   var place = document.forms["jssond"]["place"].value;
   var country = document.forms["jssond"]["country"].value;

   var json = {
       firstName: firstName,
       lastName: lastName,
       email: email,
       mobile: mobile,
       place: place,
       country: country
   };
   // Displaying is up to you

You should really look up an up to date javascript/json tutorial. document.forms[etc] is deprecated since 15 years or so.

Joshua
  • 2,932
  • 2
  • 24
  • 40