I have a problem with JSON and JQUERY. In my web application I submit some data (through an $.ajax call) to a servlet and want to receive back some informations from this servlet once it has done.
I'm using JSONObject in this way:
function check(){
$.ajax({
url: "/check",
type: "POST",
dataType: "json",
success: on_check_ok,
error: function(){
alert("something wrong happened");
},
data: {
players_code: $("#players_code").val(),
},
});
return false;
}
function on_check_ok(data) {
var json = data;
$("#display").text(json.check); //"display" is a <div> into index.html
};
and this is doPost() method in my servlet code:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
String code_array = request.getParameter("players_code");
System.out.println("Player's code is: " + code_array);
int arr = Integer.parseInt(code_array);
LinkedList<Integer> stack = new LinkedList<Integer>();
while(arr > 0){
stack.push(arr%10);
arr = arr/10;
}
int index = 0;
while(!stack.isEmpty()){
array[index] = (int)stack.pop();
index++;
}
mm.checkGuess(array);
response.getWriter().write(mm.ris + " ");
tries++;
System.out.println("TRIES: " + tries);
JSONObject obj = new JSONObject();
obj.put("check", tries);
String json = obj.toString();
out.write(json);
System.out.println("JSON " + json);
}
}
but cannot get displayed any information. Seems that JSONObject has been created correctly, since I can display it on console. I'm having hard times on getting this data back to javascripts.
That's my code, what I'm doing wrong? Or, is there an alternative way to get the same result? thanks for the help!
Related
I am developing a login function by passing json object to servlet for validation. If the login/password match with DB. The page will redirect to a main page with the login ID and corresponding profile. Or redirect to an error page if login fail. Here my coding:
jsp:
function submitForm(thisObj, thisEvent) {
var sLogin = $('#userName').val();
var sPwd = $('#userPwd').val();
var myData = {
"userName": sLogin,
"userPwd": sPwd
};
$.ajax({
type: "POST",
url: "login",
data: JSON.stringify(myData),
dataType: "json",
success: function(result){
if (result.status == "SUCCESS"){
setAttribute("ID", result.requestId);
}
}
});
return false;
}
servlet:
public class login extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
res.setContentType("application/json");
PrintWriter out = res.getWriter();
StringBuffer sbuffer = new StringBuffer();
String inLine = null;
String sUsername = "", sUserPwd = "";
try{
BufferedReader reader = req.getReader();
while ((inLine = reader.readLine()) != null)
sbuffer.append(inLine);
if (sbuffer.length() != 0){
JSONObject jsObj = new JSONObject(sbuffer.toString());
sUsername = jsObj.optString("userName");
sUserPwd = jsObj.optString("userPwd");
}
}catch(Exception e){
out.print("error");
return;
}
if (sUsername == "userA") {
JSONObject jsonSResp = new JSONObject();
jsonResp.put("status", "SUCCESS");
jsonResp.put("requestId", "1");
jsonResp.put("url", "LoginOK.jsp");
out.println(jsonResp.toString());
}
}
The servlet can get the user input login/password and perform validation. And return result back to ajax. Up next, i want to pass the data from ajax success function to new page by using set session.setAttribute() method but not works. Can anyone give hint to me to solve such problem? Thanks.
I think you need to use "rd.forward(req, res);" intead of "rd.include(req, res);" in this case.
actually, i just want to return a success page with user profile (as json object) for follow up action if login/password match with mysql database or return login fail page for invalid login. but i really don't have any idea what my coding wrong.
I'm having an issue with JSON and JSP. My Java code creates a JSON from a map, like this:
#RequestMapping(value = "/internationalWAExpose", method = RequestMethod.GET)
#ResponseBody
public String exposeWAData(final HttpServletRequest request) {
Map<String, WebAnalyticsDataValue> ajaxDataMap = new HashMap<>();
WAGlobalDataHandler globalHandler = WebAnalyticsFactory.getHandler(WAGlobalDataHandler.class);
globalHandler.setGlobalData(request, "Home", "Content");
ajaxDataMap.putAll(globalHandler.getDataMap());
JSONObject json = new JSONObject();
ajaxDataMap.forEach((k, v) -> {
try {
json.put(k, v);
} catch (JSONException e) {
e.printStackTrace();
}
});
return json.toString();
}
And I need to get the JSON on a JSP to be exposed in the elements section.
So far, I managed to set it in a JS with an Ajax call, but it shows on the console, rather than in the elements section.
AAUI.ajaxRequest({
url: '/home/ajax/internationalWAExpose',
type: 'GET',
dataType: 'json',
timeout: 50000,
onSuccess: function onSuccess(jsonResponse, textStatus) {
var webAnalyticsData = [];
for (var x in jsonResponse) {
webAnalyticsData.push(new KeyValueObject(x, jsonResponse[x]));
}
waTealiumUtils.reportEvent(webAnalyticsData, "view");
},
onError: function onError() {
},
onComplete: function onComplete() {
}
})
Any ideas? Be advised, I'm quite a newbie to JS and JSP.
There are similar links but I haven't found any solution to work for me, so I was wondering if someone could give me a working example for my scenario. I am doing an ajax get to retrieve data from the server side, so I can create charts dynamically on the client side. Do I need to include MappingJacksonHttpMessageConverter? If that's the answer can someone provide an example i can follow for that?
Java:
#RequestMapping(value="/getReportData.html", method=RequestMethod.GET, produces="application/json")
public #ResponseBody Reports getReport1Data(HttpServletRequest request)
{
System.out.println("Report 1 Page GET Method");
ModelAndView mv = new ModelAndView("report1");
if((Reports)request.getSession().getAttribute(USER_SESSION_REPORTS) != null){
reports = (Reports)request.getSession().getAttribute(USER_SESSION_REPORTS);
System.out.println("--------> Report 1 Page with session data");
return reports;
}
else{
System.out.println("--------> Report 1 Page with NO session data");
}
mv.addObject("report1", reports.getReport1());
return null;
}
Javascript:
function getData(){
$.ajax({
url: "getReportData.html",
type: "GET",
contentType: "application/json",
dataType: JSON,
success: function(report1){
console.log("success: " + report1.utilRatio.decRatio);
},
error: function(report1){
console.log("error: " + report1.utilRatio.decRatio);
}
});
}
Response Headers:
Content-Language: "en",
Content-Length: "1110"
Content-Type: "text/html;charset=utf-8"
Server: "Apache-Coyote/1.1"
Request Headers:
Accept: "/"
Accept-Language: "en-US,en;q=0.5"
Accept-Encoding: "gzip,deflate"
Content-Type: "application/json"
X-Requested-With: "XMLHttpRequest"
It looks like your request headers are wrong. You can remove the contentType setting since you are not sending data to the server and change dataType to the string value "json" instead of the variable JSON.
Also, your response headers are wrong. Just make sure you are always returning a Reports object. And you probably want to remove the html extension from that endpoint since you're just returning an object.
spring uses #ResponseBody annotaion for returning data as json .it will implicitly call the MappingJacksonHttpMessageConverter .so you need to use it.
#RequestMapping(value = "/getjson", method = RequestMethod.POST, produces = "application/json")
#Transactional
public void getJson(HttpServletRequest request, HttpServletResponse response, #RequestParam("type") String type)
throws DatatypeConfigurationException, IOException, JSONException {
JSONObject json = new JSONObject();
Map<String, String[]> parameterMap = request.getParameterMap();
List<Chart> chart=myService.getChart();
if (Chart.size()>0) {
json.put("status", "SUCCESS");
JSONArray array = new JSONArray();
for (Chart chartData: chart) {
JSONObject object = new JSONObject();
object.put("id", chartData.getRaasiId());
object.put("name", chartData.getName());
array.put(object);
}
json.put("options", array);
}
}
}
response.setContentType("application/json");
System.out.println("response======" + json.toString());
PrintWriter out = response.getWriter();
out.write(json.toString());
}
============
on the html
jQuery
.ajax({
url : controllerUrl,
dataType : 'text',
processData : false,
contentType : false,
type : 'GET',
success : function(response) {
success : function(response) {
marker = JSON.stringify(response);
json = jQuery.parseJSON(marker);
json = JSON.parse(json);
alert(json.status);
}
});
for reference:
https://rwehner.wordpress.com/2010/06/09/2-ways-to-create-json-response-for-ajax-request-in-spring3/
I'm trying to retrieve JSON from a URL and read it into my application. I am having an issue when reading the WebResponse. When the response is read, it comes back as only Symbols and is not properly formatted json.
How do I get a properly formatted JSON after streaming my WebResponse?
My Javascript is as follows:
function getJsonWM() {
//var stringedData = JSON.stringify(ajaxData);
$.ajax({
type: "GET",
url: '/Default/GetQuestionByHighestScore',
//data: JSON.stringify("{}"),
contentType: "application/json; charset=utf-8",
//dataType: "json",
success: function (data) {
var label = $("#lblResults");
var json = JSON.stringify(data);
label.text(json);
//if (data.d.Pin == undefined) {
// alert("Error: " + data.d.ErrorMessage);
//} else {
// alert("Please record the following PIN: \r\n \r\n" + data.d.Pin);
//}
},
error: function (data) {
//alert("Error: " + data.d.ErrorMessage);
}
});
}
$(function() {
//$("#btnSubmit").click(getJson);
$("#btnSubmit").click(getJsonWM);
});
My controller is as follows:
public class DefaultController : Controller
{
private const string questionUrl = "https://api.stackexchange.com/2.1/questions?order=desc&sort=activity&site=stackoverflow";
public string GetQuestionByHighestScore()
{
List<Item> list = new List<Item>();
var json = GetJson(questionUrl);
var array = JsonConvert.DeserializeObject<Item>(json);
return list.OrderByDescending(x => x.Score).FirstOrDefault().ToString();
}
public string GetJson(string url)
{
var myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
myWebRequest.Method = "GET";
myWebRequest.ContentType = "application/json";
var myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
string strResponse = String.Empty;
var encoding = Encoding.Default;
using (var reader = new StreamReader(myWebResponse.GetResponseStream(), encoding))
{
//JavaScriptSerializer js = new JavaScriptSerializer();
strResponse = reader.ReadToEnd();
}
return strResponse;
}
}
My strResponse object is as follows:
"‹\b\0\0\0\0\0\0µ\\\vÛ6¶þ+„\bÚ{G£%Q)‚ÜI“4\t6»iÓtw/”HÙšÑÕä™8Eÿû=‡”ly,y$·iÐ%òóññ¼éßi#ózñô[4|‰wÑe!›ÅÅ\"ßdMÚ¬*ÉEZ,ÿw±(ï\vY-žþ¶¨äzÓð&-‹ÅSÛv/›ZVשX<umæYžÝ¾i¶k¹x\nÝ—iÝÈJ\n`ËãX®›ëŠ7ÐÄØÅb]•IšÉë4çKì½jšuýÔ4Ó˺áñíeš/7Õe\\ææÏôêþß—7ëåóú™í°'Ëg60i½Îøöºà9’¼ÝþÄsÙÅ\"K‹Û–!ðSÜÊ;Y%Yy¯øák³²Yßn+EøûÅ\"¯yQß«!?MxVË‹Å]*ï¯ãrS40i\a&¢:ìÞ\\,긬`|1¯›k7é]Úl¯…šªM=›:®ãBÏW¯ßd‡¡¶¤R¤Í™Öô׬™Zih`®CŸfGSmiLµ·Æns\r؃Ï[#^ÉøVVFÝȸ1Š²1jÙMiðÂH\và\\ÄÒ(|Ô}`‘#®û{ÅòçŽ%Q,IË’ü]u'À’\0KÒ”„¤cIÊ[–¿_ìÁ˜oë_3ø’uY7ËJê\ažó/eaÀÞÔ«4iF‘é[¬‡L'p=Ë\n§\"3\bÆ‘y¹¬øo¸¦þhºŒ\a¡—D‚òÀŠBG¸’{^苘E2òe\v[ñ,²hÒ¸,žTÏ>üð$Âñ\aÞ4+m–“ÜÎÐ\\ï(§ ù!©#v¼a ·MG`\rÄsÁŠ4fšÃFÜIc\rÝÊ*ï#\bs4 wµ565b¸*ïb“G\0„=*ßjZÒ£E´-Q´DÑ ½niûð[o›•’$u\t(nêq!Ø—¥>sN!m\fXÙÊ¿\\–å2“H\nøh\0'jYŒ¼æÅ««7âêyµû¯÷ùÅ'35~i^_Õ/£[s½*›RËÊ/ˆºc€}¿ªÒšü$y6aíÌÌIá\0鈹gcÌG0qTXj²caÉ|¶°“g°oŒ0\b²PcÁÐÒÂÈ%#DôwµïbN÷¾Ô½¿ù–´ýû(«6ÑÖ#ÆÓ¬NøŒ˜“YkœÀºjÇ¥\\yãû¨f#oL¤IGDÂñ¤ð…å$qB=ϱœ€ZüBo–H“U&\vqS®øtíÜNÉìÓNÀ.˜‚¶ÏÂœZvh\ràÊòèl¹†4æýŠ7µc9¨7C&I§°ŠÆ=ß* É\fÕ0Gí,61ô7ÑþB½è^ö0øà"
Looks like the server returns gzip encoded response. So make sure that you have set the AutomaticDecompression property when making your HTTP request:
public string GetJson(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
using (var response = (HttpWebResponse)request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
string strResponse = reader.ReadToEnd();
return strResponse;
}
}
Also please get rid of those application/json content types. You are making a GET request which doesn't have a body - you are not sending any JSON. Also get rid of the contentType switch in your jQuery AJAX request (same reason).
I'm working on Asp.net MVC project as a single page application for error handling. I want to return json data from Application_Error method in global.asax to UI and show it by jQuery or call a controller and return partialView.
I don't want to refresh the page or redirect it to Error page.
here is the way to go
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
// if the error is NOT http error, then stop handling it.
if (!(exception is HttpException httpException))
return;
if (new HttpRequestWrapper(Request).IsAjaxRequest())
{
Response.Clear();
Response.TrySkipIisCustomErrors = true;
Server.ClearError();
Response.ContentType = "application/json";
Response.StatusCode = 400;
JsonResult json = new JsonResult
{
Data = exception.Message
};
json.ExecuteResult(new ControllerContext(Request.RequestContext, new BaseController()));
}
}
//Write This code into your global.asax file
protected void Application_Error(Object sender, EventArgs e)
{
var ex = Server.GetLastError();
//We check if we have an AJAX request and return JSON in this case
if (IsAjaxRequest())
{
Response.Write(JsonConvert.SerializeObject(new
{
error = true,
message = "Exception: " + ex.Message
})
);
}
}
private bool IsAjaxRequest()
{
//The easy way
bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest")
|| ((Request.Headers != null)
&& (Request.Headers["X-Requested-With"] == "XMLHttpRequest"));
//If we are not sure that we have an AJAX request or that we have to return JSON
//we fall back to Reflection
if (!isAjaxRequest)
{
try
{
//The controller and action
string controllerName = Request.RequestContext.
RouteData.Values["controller"].ToString();
string actionName = Request.RequestContext.
RouteData.Values["action"].ToString();
//We create a controller instance
DefaultControllerFactory controllerFactory = new DefaultControllerFactory();
Controller controller = controllerFactory.CreateController(
Request.RequestContext, controllerName) as Controller;
//We get the controller actions
ReflectedControllerDescriptor controllerDescriptor =
new ReflectedControllerDescriptor(controller.GetType());
ActionDescriptor[] controllerActions =
controllerDescriptor.GetCanonicalActions();
//We search for our action
foreach (ReflectedActionDescriptor actionDescriptor in controllerActions)
{
if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper()))
{
//If the action returns JsonResult then we have an AJAX request
if (actionDescriptor.MethodInfo.ReturnType
.Equals(typeof(JsonResult)))
return true;
}
}
}
catch
{
}
}
return isAjaxRequest;
}
//Write this code in your ajax function in html file
<script type="text/javascript">
$.ajax({
url: Url
type: 'POST',
data: JSON.stringify(json_data),
dataType: 'json',
cache: false,
contentType: 'application/json',
success: function (data) { Successfunction(data); },
error: function (xhr, ajaxOptions, thrownError) {
var obj = JSON.parse(xhr.responseText);
if (obj.error) {
show_errorMsg(obj.message);
}
}
});
</script>