3

I am trying to pass some variables through JSON from JSP to servlet through ajax call. But i am getting null value at servlet side. Please some one help me on to find out where i am making mistake/ what i missed

//JSON	
		var masterdata = new Object();
	    masterdata.grn = $('#grn').val();
	    masterdata.pono = $('#pono').val();
	    masterdata.podt = $('#podt').val();
      
//call the servlet to insert the data only when error = 0
		if (error != 1){
			$.ajax({
				url : 'insertserv',
				type: 'POST',
				dataType: 'json',
		        data: {test : JSON.stringify(masterdata)},
		        contentType: 'application/json',
		        mimeType: 'application/json',
				success : function(data) {
							alert('Hi');
						}			
		          });
		    }
		else{
			alert("Save cannot be performed. Please check the entered data!");
		}
	  	});

public class insertserv extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		System.out.println("I am inside insert");
		String masterdata = request.getParameter("test");
		System.out.println("masterdata :  "+masterdata);
		
		response.setContentType("text/plain");
	}
}

2 Answers 2

2

Replace your ajax code with my code...

//JSON	
		var masterdata = new Object();
	    masterdata.grn = $('#grn').val();
	    masterdata.pono = $('#pono').val();
	    masterdata.podt = $('#podt').val();
      
//call the servlet to insert the data only when error = 0
		if (error != 1){
			$.ajax({
				url : 'insertserv',
				type: 'POST',
				dataType: 'json',
		        data: JSON.stringify({"test" :masterdata}),
		        contentType: 'application/json',
		        mimeType: 'application/json',
				success : function(data) {
							alert('Hi');
						}			
		          });
		    }
		else{
			alert("Save cannot be performed. Please check the entered data!");
		}
	  	});

To get data in servlet

 BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
      String json = "";

            if (br != null) {
                json = br.readLine();
            }
 JSONObject wholedata= new JSONObject(json);

now the object wholedata has a your json..

if you are using JSON.stringify() then you have to use BufferedReader in servlet , You can use request.getparameter in servlet when you are passing data in URL of servlet.

Sign up to request clarification or add additional context in comments.

11 Comments

Thanks for given me the correct path. Could you please little more clear on how should i proceed to get all variables
To get data from wholedata you can do like JSONObject testdata = wholedata.getJSONObject("test"); Then to get particular element write testdata .getString("grn"); This is only for example you can do it for all your Three varibles (grn,pono,grn)
i am getting error at JSONObject wholedata= new JSONObject(json);" The constructor JSONObject(string) is undefined". and i have imported org.json.simple.*; too
hey Jsel first print the String json if it prints well then we are sure that our data is in servlet , if it doesn't print anydata then we have to optimize the code. if data will print then we can get variable's data from using code..
fine. Thanks a lot for your help!
|
0

If your backend is responding with json content then only dataType:"json" works. Try change the response type:

response.setContentType("application/json");  

Because your ajax is expecting json from the backend with dataType:"json",.

or vice-versa.

change the dataType to text: dataType:"text", as the response header says response.setContentType("text/plain");. But in this case you have to use JSON.parse() to parse the json string.

//JSON  
var masterdata = new Object();
masterdata.grn = $('#grn').val();
masterdata.pono = $('#pono').val();
masterdata.podt = $('#podt').val();

//call the servlet to insert the data only when error = 0
if (error != 1) {
  $.ajax({
    url: 'insertserv',
    type: 'POST',
    dataType: 'text', //<------change this
    data: {
      test: JSON.stringify(masterdata)
    },
    contentType: 'application/json',
    mimeType: 'application/json',
    success: function(data) {
      alert('Hi');
    }
  });
} else {
  alert("Save cannot be performed. Please check the entered data!");
}
});

3 Comments

changed response as application/json. still getting null
@Jsel i can see you are not returning a valid json instead change the dataType to text.
i have modified as u mentioned in snippet. but getting same null:(

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.