Am getting a json data from servlet to JSP. Am getting the response from servlet checked in browser console. Attached the screenshot. I have given below the servlet and JSP code. Am making a ajax call to servlet to retrieve the json data. But from servlet response is coming but in ajax call its not going inside success function. How can i read this data in JSP and i need to use this JSON in javascript to retrieve it.
Am new to JSP & Servlet. I have tried this much. Can anyone help here please to read it and retrieve in JSP?
Thanking in Advance
Servlet Code
response.setContentType("application/json");
response.setHeader("cache-control", "no-cache");
PrintWriter out = response.getWriter();
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
out.println(json.toString());
out.flush();
JSP Code with AJAX Call
$.ajax({
url: '<%=request.getContextPath()%>/home',
type: 'POST',
data: {
'action': 'getBugReport',
'dateString':document.getElementById("daterangePicker").value,
'projectName': 'All'
},
success: function(responseText) {
},
error: function () {
}
Response from Servlet
Related
I am running a simple website that communicates with a TestServlet using ajax and jquery. The servlet gives a JSON object using doGet(), as follows:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String json = "{\"name\": \"jsontest\",\"type\":\"jsonobject\"}";
response.getWriter().append(json);
}
When a button is pressed on the page, an ajax request is issued as follows:
$.ajax({
type: "GET",
url: "test",
data: "",
dataType: "json",
success: function(reply) { window.alert("Success\n"+reply); },
error: function(err) { window.alert(err); }
});
The request obtains success, but reply is null and I get from web console:
XML Parsing Error: not well-formed
Location: http://localhost:8585/web/test
Line Number 1, Column 1: {"name": "jsontest","type":"jsonobject"}
I tried to specify mimeType: "application\json" but I got the same behavior. Instead, when I don't specify dataType or I put contentType: "json" I succeed to read correctly the JSON string but still I get the XML Parsing Error.
Can anyone explain why I get a XML Parsing Error while I am supposing to exchange JSON?
NOTE: I'm using Firefox and Tomcat9.
Thank you in advance.
Simply, I found out that while I was expecting json content in the request through dataType, the servlet was not specifying that its response was coded with that type too.
Adding:
response.setContentType("application/json");
solved the problem.
I am using Extjs 5.1.3. I have post request with params as-
{"root":{"countryId":"458","ruleId":"3386","ruleName":"Test1 \\","ruleType":"CELL_STORE","opType":"DETAILS"}}
I am creating ajax request as-
Ext.Ajax.request({
method: 'POST',
url: appurl.fetchRuleDetails,
params: win.jsonData,
callback: function(option, success, response){
})
})
From server side, response is coming as-
{
"rules":[
{
"countryId":"458",
"ruleId":"3386",
"ruleName":"Test1 \\",
"ruleType":"CELL_STORE",
"ruleParts":[
{
"seq":"1",
"attrId":"6",
"attrName":"Store Type",
"op":"=",
"val":"dsafdaf",
"charType":"GLOBAL_CHAR"
}
]
}
],
"Status":{
"StatusFlag":true,
"StatusCode":"SUCCESS",
"StatusMessage":"SUCCESS"
}
}
But in Ajax request's callback function, we are receiving response.responseText as-
Request Media Type[application/json] Error! Request Body is not JSON format.
My guess is like issue is because of rulename value as "Test1 \".
So can someone please help me whats missing.
The error message is not an ExtJS error message. If you receive an ExtJS error related to invalid JSON, it will look like this:
Uncaught Error: You're trying to decode an invalid JSON String: TestTest
My best guess is that the error message comes from the server, because it expects you to send your request as JSON. Right now you are sending it as FormData. To send the request as JSON, you have to put your object in the jsonData config and leave the params config undefined:
Ext.Ajax.request({
method: 'POST',
url: appurl.fetchRuleDetails,
jsonData: win.jsonData,
callback: function(option, success, response){
})
})
For future questions regarding server-client communication, please keep in mind that you should first check in your browser network tab what you send to the server and what the response from the server really is.
Is it possible in one JSP to make a jQuery ajax callback to another JSP and have data returned?
I am trying to make the ajax call to Page2.jsp in the $(document).ready call in Page1.jsp
I am attempting to get JSON returned by "Page2.jsp"
I am running Tomcat locally to test.
I am seeing the JSON printed to the console, but not returned to the original calling method in Page1.jsp
Any ideas?
Page1.jsp
$(document).ready(function(){
$.ajax({
url : 'Page2.jsp',
dataType: 'json',
success : function(json)
{
var obj = jQuery.parseJSON(json);
}
});
});
Page2.jsp
<%#page contentType="application/json; charset=UTF-8"%>
<%#page import="org.json.simple.JSONObject"%>
<%
JSONObject json = new JSONObject();
json.put("amount","55.00");
json.put("tax","1.00");
String jString = JSONObject.toJSONString(json);
PrintWriter out = response.getWriter();
out.println(jString);
out.close();
%>
I tried the code in your question and the jQuery.parseJSON() code throw the following error: "SyntaxError: JSON.parse: unexpected character". On debugging I saw that the servlet code generated by tomcat includes out.write("\r\n"); I suspect that these character are causing the syntax error.
Nevertheless in the javascript I tried accessing the returned object using the dot notation without parsing it and I was able to so as if it were a JSON object. It appears that it is not necessary to parse the returned object.
The only modification I made to the JSP code was to remove the lines PrintWriter out = response.getWriter(); and out.close();
I am trying to convert a regular old controller I was using to an API controller and am having a little bit of difficulty. What these series of functions do is, in the jQuery, it iterates over a file containing all the usernames of employees and for each username it makes a call to the PopulateEmployee method in my webapi controller which should return JSON and then populate a results div.
When manually navigating to
..domain../staffinformation/populateemployee/employeeusername
I get the error
This XML file does not appear to have any style information associated with it. The
document tree is shown below.
<Error>
<Message>
The requested resource does not support http method 'GET'.
</Message>
</Error>
Please note that the div it will be populating is a partial view in an Umbraco CMS page and I don't think that is the problem but if you guys think differently please tell me.
There has to be something I am missing either with webAPI routing or something else.
Thanks for your help.
Here's the codez.
Please notice that this method has the HttpPost tag
public class StaffInformationController : ApiController
{
[System.Web.Http.ActionName("PopulateEmployee")]
[System.Web.Http.HttpPost]
public StaffListing PopulateEmployee(string id)
{
//do error checking on input
StaffListing staffListing = new StaffListing(id);
//populate other fields
return staffListing;
}
}
The routing set up for the api controller
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
The jQuery call specifying use of 'POST', please forgive the trickiness of the recursive call in this function.
function getEmployeeObjectByIndex() {
$.ajax({
url: $('#root').val() + '/api/StaffInformation/PopulateEmployee',
type: 'POST',
async: true,
contentType: 'application/json, charset=utf-8',
data: JSON.stringify({ 'username': lines[i] }),
success: function (staffObject) {
if (!(staffObject.Name == undefined)) {
buildHtmlStrings(staffObject);
}
i++;
getEmployeeObjectByIndex(); //recursive call
}
});
}
manually navigating to that address throws the error because, when manually navigating you are doing a GET (and your method only allows POSTs).
You should fire up Fiddler and watch the ajax POST request and response to see how the server is responding / your request is being made
Jquery ------> web api
Web API has one property i.e. CONTENT NEGOTIATION means you send any data and accept any data as you want.
$.ajax({
contentType: 'application/json, charset=utf-8',
// this is sending your data of datatype json to server, here you send any type of data
accept: 'application/json',
//this is receiving/getting data form server to client...
// SO HERE YOU GET JSON DATA AS YOU WANT only mention which data of datatype u want...
//if you sending xml and you want json so only write accept as json it get automatically converted into your required datatype..by MediaTypeFormatter
});
Updated: I'm posting HTML FORM data but expecting to receive JSON data. I am not trying to POST JSON data.
I am trying to get a JSON response back from doing a HTML FORM POST request. I have successfully received a JSON back when using a simple HTML FORM POST request (i.e. not AJAX). My JSON response from the HTML FORM POST is this:
{"success":true,"data":1234567}
The problem occurs when I try to handle the request and response with jQuery's .ajax().
$.ajax({
type: "POST",
url: URL,
data: data1,
dataType: "json",
success: function(data, textStatus, jqXHR) {
alert ("success");
},
error: function(xhr, status, error) {
alert ("Error: " + error);
}
});
After running the above code and debugging in Firebug, it appears that the POST request is going through, but something is going wrong on the handling of the response. Firebug tells me the following regarding the HTTP response from the POST request:
Response Headers
Cache-Control private
Content-Length 31
Content-Type application/json; charset=utf-8
...
So it appears that the 31 bytes of data is being sent. However, when debugging the actual Javascript, the error function gets called and the xhr object is this:
Object { readyState=0, status=0, statusText="error"}
I know the jQuery.ajax() document states that "In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown." However, I believe my JSON is valid as I have checked it at jsonlint.com.
What else could be going wrong?
It looks to me like you are getting a server error. I would check the status code of the response and fix whatever is causing the request to fail on the server.
your getting an error because data1 is not formatted in json, so when it receives the data it gets a parse error. data1 needs to be formatted:
data1={"apikey":apikey,
"firstname":fName
}
I was having the same problem. It seems that this is an issue with Cross Domain.
Finding this SO answer: https://stackoverflow.com/a/7605563/154513
helped me.
Some times Jquery return Internal Error 500 for currectly data.
There is example for read the same json data withour error
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://reqres.in/api/products/3", true);
xhr.onload = function(){
console.log(xhr.responseText);
};
xhr.send();