not able to get JSON string in servlet - javascript

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");
}
}

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.

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!");
}
});

Related

Cannot retrieve data from ajax with request

I'm having problems retrieving data from an ajax post in an easy aplication, just making some tests.
I'm working with something easy:
I have 2 classes:
Controller.java:
#RequestMapping(value = "/urlpost", method = {RequestMethod.GET, RequestMethod.POST} )
public urlPostTest(HttpServletRequest request, HttpServletResponse response) {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("post_name");
String age = request.getParameter("post_age");
System.out.println("His name is: " + name);
System.out.println("His age is: " + age);
}
And
PostingClass.js
function posting(){
$.ajax({
url: 'urlpost',
method: 'POST',
data: {
'post_name': "Peter",
'post_age': "22"
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
console.log("Send data: SUCCES.");
}
});
}
The ajax goes correctly to the url, but the request is always null.
What could be the problem?.
Thanks.
request.getParameter("post_name"); // works on application/x-www-form-urlencoded
To get the data from a application/json request, use something like this:
String jsonStr = IOUtils.toString(request.getInputStream());
JSONObject jsonObj = new JSONObject(jsonStr);
String name = getString("name");

MVC maxJsonLength error

I'm struggling with maxJsonLength error.
I'm passing very long xml string (~4MB) from controller action to javascript method in a View. This method proceses data and send it back with AJAX to another controller method, and here I'm getting error.
I've set MaxJsonLength in JsonResult object, in the controller method, and the is no problem with passing this string from controller to view.
But when I'm try to pass it back after processing I'm getting error.
This is my Controller method whitch prepare data:
private JsonResult PrepareXml(int someId)
{
// preparing data...
string xmlData = "..."; //(~4Mb)
JsonResult res = Json(xmlData);
res.MaxJsonLength = 10000000; // 10Mb
return res;
}
And this is my Controller method whitch is trying to proces data passed from ajax method:
private JsonResult GetProcesedXml(string resultXml)
{
// This method is not ivoking
}
And below is my script method:
var data = {
someId: rowId,
};
$.ajax({
type: "POST",
url: "MyController/PrepareXml",
data: data,
contentType: "application/json; charset=utf-8",
success: function (result) {
// proces the result (big xml file)
//...
var processedResult = ""; // size of processedResult is a little bit bigger than 'result'
var data2 = {
resultXml: processedResult
};
$.ajax({
type: "POST",
url: "MyController/GetProcesedXml",
data: data2,
contentType: "application/json; charset=utf-8",
success: function (r) {
alert('success');
},
error: function (data) {
alert(data.responseText);
}
});
}
});
What I've tried already:
<add key="aspnet:MaxJsonDeserializerMembers" value="2147483647" /> //(max value)
<requestLimits maxAllowedContentLength="2097151000" /> //(max value)
<httpRuntime maxRequestLength="10000" /> //(~10MB)
I've found some workaround for this problem.
I've changed content type in Ajax method to "text/plain" and used JSON.stringify on my xml file data.
var data2 = { resultXml: processedResult };
$.ajax({
type: "POST",
url: "MyController/GetProcesedXml",
data: JSON.stringify(data2),
contentType: "text/plain",
success: function (r) {
alert('success');
},
});
Another change is in controller. I've read file from input stream and parse it to form JSON type:
private JsonResult GetProcesedXml()
{
JObject json = null;
Stream request = Request.InputStream;
using (StreamReader sr = new StreamReader(stream))
{
stream.Seek(0, System.IO.SeekOrigin.Begin);
json = JObject.Parse(sr.ReadToEnd());
}
string xmlSigninigResult = json["resultXml"].ToString();
// rest of the method
}

Handler execution resulted in exception: Required MultipartFile parameter 'file' is not present

My Controller code :
#RequestMapping(value = "/rest/auth/admin/test/responseTest", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<ResponseVO> responseTest(#RequestParam("file") MultipartFile file,
#RequestParam(value = "testId", required = true) long testId) {
I have already added the multipartResolver bean to my application-context.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
My javascript code :
var fd = new FormData();
fd.append('file', $('input[type=file]')[0].files[0]);
fd.append("label", "WEBUPLOAD");
var headers = {};
headers[Constants.XCSRFTOKENCookieName] = util.getCookie(Constants.XCSRFTOKENCookieName);
var url = "rest/auth/admin/test/responseTest?responseTest=123";
var dataType = "json";
var contentType = "application/json";
$.ajax({
url: url,
type: "POST",
data: fd,
dataType: dataType,
async: isAsync,
headers: headers,
enctype: contentType,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function(result, status, jqXHR) {
resultObj = result;
if (successCallBack != null) {
successCallBack(resultObj);
}
//util.hideLoader();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error : " + errorThrown);
resultObj = jqXHR.responseJSON;
if (errorCallBack != null) {
errorCallBack(resultObj);
}
//util.hideLoader();
}
});
When I am calling the above Ajax I am getting the following error at server side.
[org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver] > logException() : 186 - Handler execution resulted in exception: Required MultipartFile parameter 'file' is not present
Please help me to resolve this issue.
I would have thought the contentType header for this should be multipart/form-data instead of application/json?

Read HttpResponseMessage in Ajax onSuccess

This is my APIController method -
[HttpPost]
public HttpResponseMessage Get(string url) {
string responseString = GetWebApiData(url);
HttpResponseMessage response = new HttpResponseMessage();
if (!string.IsNullOrEmpty(responseString) && responseString.ToString().IsValid()) {
response.ReasonPhrase = "Valid";
response.StatusCode = HttpStatusCode.OK;
} else {
response.ReasonPhrase = "Invalid";
response.StatusCode = HttpStatusCode.BadRequest;
}
return response;
}
This is my ajax call to above method -
$.ajax({
type: "POST",
url: "http://localhost:50/api/DC/" + formData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, textStatus, xhr) {
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
I am not able to read the HttpResponseMessage returned by the API Method. For both the conditions of OK and Bad Request, status code returned in 'xhr' of ajax method is '204' & 'No Content'. I need to validate based on response code. Any help pls!
I tried success: function(response) too, response was undefined.
The response is 204 No content because you literally don't add any content. All you're doing is setting the response code. You can add content to the response like this:
response.Content = new StringContent("Return data goes here");
Alternatively use the Request.CreateResponse()/CreateErrorResponse() to create the HttpResponseMessage for you:
[HttpPost]
public HttpResponseMessage Get(string url)
{
string responseString = GetWebApiData(url);
if (!string.IsNullOrEmpty(responseString) && responseString.ToString().IsValid())
{
return Request.CreateResponse("Valid"); // I'd suggest returning an object here to be serialised to JSON or XML
}
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid");
}

Ajax send large data MVC4

I'm Trying to send large Data amount using ajax , it returns 404 error Not found , and if I send small amount of Data it respond with 200 and work Normally
here is my Code
var str = myDiagram.model.toJson();
document.getElementById("mySavedModel").value = str;
myDiagram.isModified = false;
$.ajax({
dataType: "json",
url: "/Workflow/PraseJson/?diagram=" + str
}).done(function (x) {
});
and Code for Controller
public void PraseJson(string diagram)
{
object yourOjbect = new JavaScriptSerializer().DeserializeObject(diagram);
}
I do not know how to solve this Issue, Can anyone help ?
Try using POST to send data
$.ajax({
dataType: "json",
type: "POST",
data: {diagram: str },
url: "/Workflow/PraseJson/
}).done(function (x) { });
[HttpPost]
public void PraseJson(string diagram)
{
object yourOjbect = new JavaScriptSerializer().DeserializeObject(diagram);
}

Categories

Resources