0

Stackoverflow team members.

I am struggling to get the solution of my problem. Actually in my application I want to make use of Jquery and Json with Servlet. In my Application There is one JSP Servlet page to enter detail entry like user_name, user_address etc.

All this data will be send to database using jquery ajax. Now I want to retrieve all records that are inserted to database using json in the form of json array object.

I am able to insert record to database but I don't know how to get them back from database to json object array so i can use them again. in some another jsp servlet page.

Help me solve my problem.

Best Regards
Yogendra

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
yaryan997
  • 483
  • 3
  • 10
  • 18

2 Answers2

1

First of all you need to do an Ajax call to your servlet, see following code :

    $.getJSON("yourServlet", function(json) {
    alert("JSON Received Data: " + json);
    //Logic to Parse the received JSON
    });
   </script>

Secondly construct JSON object at server side with its specific format, something like :

{
    "firstName": "John",
    "lastName": "Smith",
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    },
    "phoneNumbers": [
        "212 732-1234",
        "646 123-4567"
    ]
}

Now Construct a list of inserted records in the database, see following sample code that showing how to construct list of records in JSON :

List mybeanList = new ArrayList();
mybeanList.add(myBean1);
mybeanList.add(myBean2);

JSONArray jsonArray = JSONArray.fromObject(mybeanList);
System.out.println("==== : "+jsonArray);

Map map = new HashMap();
map.put("beanlist", jsonArray);

JSONObject jsonObject = JSONObject.fromObject(map);
return jsonObject;

Finally parse the received JSON response inside your jsp (using javascript or any other alternatives)...

Go through with this tutorial, if you face any trouble with JSON.

Nirmal
  • 4,789
  • 13
  • 72
  • 114
0

Well you need to establish a connection with your database server side, pull the records out of the database (possibly filtering based on data from the ajax request? look at data attribute for .getJSON) then your server needs to format this in JSON. In PHP you'll use json_encode($data_array) -- then simply echo this back to the client. For the jQuery request:

   $.getJSON('http://site.com/ajax/get-latest-posts', {
         success: function(jsonObject) {
             // jsonObject[0].author, for example.
         }
   });
Gary Green
  • 22,045
  • 6
  • 49
  • 75