Dynamic ChartJS - javascript

I have recently discovered chartJS and adore the design. Now I am struggling to get the data dynamic.
My goal is to retrieve data from the postgresDB in my Java Controller and route it to the javascript file to display it in the jsp files. But I don't know how to access the data in the java files out of the javascripts.
Thank you for your time and helping me!
Yours, Janick
Edit:
In the controller I've tried to put a JSON Object as String in the request:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
JsonObject json = new JsonObject();
json.addProperty("20210701",100.00);
json.addProperty("20210702",101.00);
json.addProperty("20210703",102.00);
String strJson = json.toString();
request.setAttribute("json",strJson);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
and in the Javascript file:
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
console.log(params);

Unfortunately I do not know how to do this with Java? But in .NET with ASP you can use Ajax or PageMethods to call a server-side web service or web method and query the database and then use Chart.js dynamically. You can of course control the web service with parameters and in the return object you can write arrays or lists for the result and then use a callback method to make the chart dynamic.

Related

Avoid displaying returned data from Spring #ResponseBody on browser

Okay, curerntly I am displaying some data on a html page. I have used jquery ajax call which get the data from the specific url on spring MVC application and return data and then use javascript to display data in the table.
#RequestMapping(value = "/students", method = RequestMethod.GET)
#ResponseBody
#JsonView(Views.PublicView.class)
public ArrayList<Student> getAdminsList(HttpSession session) {
//return data
}
Now, my question is, I get data as I required via ajax, but I do get data displayed in the browser if I just go through url: www.example.com/students - will display JSON data.
Is there anyway to avoid display this data not in browser but only in ajax call?
Anyway, I just found the answer for this after lots of googling and I thought sharing it would be good thing. So, basically what is the logic for this restriction is that, whenever a call is made from ajax a special header named X-Requested-With with a value of XMLHttpRequest is attached to the request. the only thing I have to do is check this parameter on my controller.
#RequestMapping(value = "/accounts", method = RequestMethod.GET)
#JsonView(View.Accounts.class)
public List<Account> getAccounts() throws JsonProcessingException {
if(!"XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
log.info("Request is from browser.");
return null;
}
List<Account> accounts = accountService.findAccounts();
return accounts;
}
you can read the full article on this blog. http://www.gmarwaha.com/blog/2009/06/27/is-it-an-ajax-request-or-a-normal-request/
Maybe feels like being a problem[#JsonView(Views.PublicView.class)]. You check PublicView.class
Read to description. link : enter link description here
#RequestMapping(value = "/accounts", method = RequestMethod.GET)
#JsonView(View.Accounts.class)
public List<Account> getAccounts() throws JsonProcessingException {
List<Account> accounts = accountService.findAccounts();
return accounts;
}

asp.net ".d" failure parsing JSON on client side

The configurations to my asmx page are as follows
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using Time.CSharpclasses;
/// <summary>
/// Summary description for LiquidityMonthAjax
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class LiquidityMonthAjax : System.Web.Services.WebService
On the client side my response is mysteriously coming back with a different type of item I have never seen before, even though I use the same methods to parse it to JSON.
#document
<string xmlns="tempuri.org">
["Presbyterian Health","Devon","LABS","Self-Pay","Sagamore"]
</string>
I don't understand what's different. I usually get my json from .d.
Using Asp 4
There must be some dependency I'm missing but I dont know if it is client side or server.
[WebMethod]
public string getUniqueFinClass()
{
DataTable dt = ExcelManager.CreateDataTableFromSql(new XMLManager("liquiditymonth.xml").getReport(Xmls[6]));
var r = from row in dt.AsEnumerable() select (string)row["FinancialClass"];
return DictToJSON.serializeJSONObject(r.ToList());
}
The former is the method that gives me problems the serializeJSONObject method
follows:
public static String serializeJSONObject(Object items)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = 2147483644;
return serializer.Serialize(items);
}
I really don't think is that method that's the problem because I've used it a hundred times before with success.
Some versions of the .Net platform return d some do not. Try putting something like this in your code:
var data = (response.hasOwnProperty("d")) ? d : response;
Now data contains the response no matter which version of .Net is being used making your client code more robust.
Dave Ward did a blog on this: http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/
Apparently the problem was client side. I forgot to stringify my object so jquery politely wrapped the aguments up in the url query instead. A function of ASP.net says that if the request is not JSON then the response is XML forsaking the request header type and any attempt of the programmer to make it JSON.
Refer to this link under JSON,Objects and Strings: oh my!
http://encosia.com/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/

URL Routes with Java Servlets

I wanted to know if there is a way to do similar code in java servlet like I do in express.js
In express I can say for example:
app.get('/:name',function(bla bla)){}
the :/name its a parameter in which the url of the get can be
localhost/kevin
localhost/joe
or whatever... This is great because I can take then for example that name (request.params.name) and so something with it. And it is also great because there is no limit(As far as I know) as to how many routes I can create, it just serves as a placeholder.
Is there a way I can do this using Java servlets?? I want to be able to have an html page that when I click a button it goes to localhost/button1 If I click another button it goes to localhost/button2.. and so on.. But also I'm letting the user create buttons dynamically so I don't want to create jsp pages beforehand, I just want the servletto create one..?
Thanks
Almost. With help of a prefix mapping /foo/* and HttpServletRequest#getPathInfo().
#WebServlet("/name/*")
public class NameServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getPathInfo().substring(1);
// ...
}
}
Invoke it as
http://localhost:8080/context/name/kevin
http://localhost:8080/context/name/joe
...
You can optionally map the servlet on /*, but then it will act like a global front controller which isn't necessarily a good idea as you'd have to take static resources like CSS/JS/images and such into account.
In case you actually intend to create a REST service, rather look at JAX-RS instead of "plain vanilla" servlets. It would further reduce boilerplate code. See also a.o. Servlet vs RESTful.

#Produces({"application/x-javascript"}) not working in spring mvc version 4.0.5.RELEASE

I have created a spring application and i am also using webservices.
I want to use jsonp callback function for which the media type should be {"application/x-javascript"}. This seems not to be working. it is returning json object and not javascript.
Here is the code..
#RequestMapping(value = "widget", method = RequestMethod.GET)
#Produces({"application/x-javascript"})
public #ResponseBody JSONWithPadding displayWidgetPage(Model model, HttpServletResponse
response,HttpServletRequest request)
{
String callback = request.getParameter("callback");
PointsInfo pointsInfo =new PointsInfo();
pointsInfo.setUsername("json");
return new JSONWithPadding(pointsInfo,callback);
}
I checked using the rest client...
It says the content type is : Content-Type: application/json;charset=UTF-8
It has to be : Content-Type: application/javascript;charset=UTF-8
I think that you're mixing Jersey's #Produces and JSONWithPadding with Spring MVC, and Jersey's #Produces will not take any effect there.
If you're looking for a way to implement JSON-P with Spring MVC only, take a look at
http://patrickgrimard.com/2010/07/28/tutorial-implementing-a-servlet-filter-for-jsonp-callback-with-springs-delegatingfilterproxy/
or if you're able to upgrade to the version 4.1 or above
http://spring.io/blog/2014/07/28/spring-framework-4-1-spring-mvc-improvements
You are using a Spring version older than 3.1.1.RELEASE. If you are looking to set your response's media type, it should be in the RequestMapping annotation like this:
#RequestMapping(value = "/list/rideLogs/{rideId}", method = RequestMethod.POST,
produces = YOUR_MEDIA_TYPE)
That being said application/javascript isn't a valid media type for Spring. You can refer to values of MediaType class.
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/MediaType.html

How to return JSON from ASP.NET .asmx?

I have the following test method:
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<System.Web.Script.Services.ScriptService()> _
Public Class DemoService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function GetCustomer() As String
Return "Microsoft"
End Function
End Class
Even with the ResponseFormat attribute added the response is still being returned as XML rather than JSON.
Thoughts appreciated.
I'm a bit late to this question, but hopefully this helps you or anyone else stumbling onto this thread later.
You definitely can use ASMX services to communicate in JSON.
Your service code looks okay. Since you aren't showing how you're calling it, I'll bet that's where your problem lies. One requirement for getting JSON out of ASMX "ScriptServices" is that you must call them with the correct content-type header and you must use a POST request. Scott Guthrie has a good post about the reasoning behind those requirements.
So, if you just request DemoService.asmx/GetCustomer in a browser, you're going to get XML. However, if you make a POST request with an application/json content-type, you'll get the same result serialized as JSON.
If you're using jQuery, here's an example of how you would request your DemoService on the client-side:
$.ajax({
type: "POST",
contentType: "application/json",
url: "DemoService.asmx/GetCustomer",
data: "{}",
dataType: "json",
success: function(response) {
// Prints your "Microsoft" response to the browser console.
console.log(response.d);
}
});
More here: http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
Do you have .NET 3.5 or greater installed?
ScriptServiceAttribute is in .NET 3.5 and 4.0.
Also, clear your ASP.NET temp files, the dynamic proxy could be cached.
Why not just use an ashx file? It's a generic handler. Very easy to use and return data. I use these often in place of creating a web service as they are much lighter.
An example of the implementation in the ashx would be:
// ASHX details
DataLayer dl = GetDataLayer();
List<SomeObject> lst = dl.ListSomeObjects();
string result = "";
if (lst != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
result = serializer.Serialize(lst);
}
context.Response.ContentType = "application/json";
context.Response.Write(result);
context.Response.End();
If you do need to use a web service though you could set the ResponseFormat. Check out this SO question that has what you are looking for:
How to let an ASMX file output JSON
This is what I do, though there is probably a better approach, it works for me:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string retrieveWorkActivities(int TrackNumber)
{
String s = {'result': 'success'};
return s.ToJSON();
}
If you're restricted to the 2.0 Framework, you can use the JavaScriptSerializer, from the System.Web.Extensions assembly, like this (in C#):
[WebMethod()]
[ScriptMethod()]
public static string GetJsonData() {
// data is some object instance
return new JavaScriptSerializer().Serialize(data);
}
I've used ashxes for this problem too. To be honest I didn't know webservices had that ResponseFormat attribute. That said I think I still prefer the ashx route for lightness and control.
There's some peripheral details left out here, to concentrate on the bit you'd need.
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Namespace Handlers.Reports
Public MustInherit Class Base
Implements IHttpHandler, SessionState.IRequiresSessionState
Protected data As String()() = Nothing
Private Shared ReadOnly JsonContentType As String = "application/json"
Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
Try
Me.GetData()
Me.BuildJsonResponse(context)
Catch ex As Exception
End Try
context.Response.End()
End Sub
Private Sub BuildJsonResponse(ByVal context As System.Web.HttpContext)
context.Response.AddHeader("Content-type", Base.JsonContentType)
Dim json = Me.BuildJson()
context.Response.Write(json)
End Sub
Private Function BuildJson() As String
If Not Me.data Is Nothing Then
Return String.Format("{{data: {0}, pageInfo: {{totalRowNum:{1}}}, recordType: 'array'}}", JsonConvert.SerializeObject(Me.data), Me.totalRows)
End If
Return String.Empty
End Function
End Class
End Namespace
Sorry to answer for old post. if we need to return json of a specific object then we can follow this approach too.
[WebService(Namespace = "http://contoso.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]System.Web.Services.WebService
[ScriptService]
public class services :WebService
{
[WebMethod(CacheDuration = 60)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<TestObject> GetObjectCollection()
{
return YourService.GetObjectCollection().ToList();
}
}
good article exist from this link https://cmatskas.com/getting-json-data-using-an-asmx-web-service/

Categories