0

I have a json string which I want to send it to servlet when confirmed in an alert box from where it will be posted into a database using my sqlserver. can you please help me with this? following is my ajax code to send to server. What coding do I need to do in server side to post it in to the database.

var a ={
        Message:messagecreated,
        Type:messageType  
 } ;  
   var jsonString=JSON.stringify(a) ;
   if(confirm("Do you want to save this message? \n\n"+ jsonString))
   {
       $(function(){
     $.ajax({
  type: "POST",
  url: "CreateMessage",
  async:true,
  cache:false,
  data: jsonString,
  contentType: "application/json",
  success: function(response) {
        alert(response);
    },
    error: function(e){
   alert('Error: ' + e);
    }
dbc
  • 104,963
  • 20
  • 228
  • 340
user3049602
  • 41
  • 1
  • 8
  • BalusC how is is duplicate? – user3049602 May 07 '16 at 18:19
  • It explains how to properly send an ajax request to a servlet and how to collect the data. Once you have the data in Java variables, and thus ajax and servlets have finished their job, then you can advance inserting that data in the DB the usual way. – BalusC May 07 '16 at 19:00
  • thank you.is my ajax code alright then? – user3049602 May 08 '16 at 11:01
  • i tried to put my data but its not going. I used following code in java servlet: – user3049602 May 09 '16 at 21:18
  • response.setContentType("application/json"); PrintWriter out = response.getWriter(); JsonObject jsonString = new Gson().fromJson(request.getReader(), JsonObject.class); String mess = jsonString.get("Message").getAsString(); String ty = jsonString.get("Type").getAsString(); con = DBConnector.connectDb(); PreparedStatement ps = con.prepareStatement("insert into messages values(?,?)"); ps.setString(1, mess); ps.setString(2, ty); ps.executeQuery(); – user3049602 May 09 '16 at 21:19

0 Answers0