Pass Json Object from Play! framework to HighCharts JS - json

http://www.playframework.com/documentation/2.1.x/JavaTodoList
Using the above tutorial as a reference, I have created an application which sends data from the model to view via the Application controller.
I have managed to display the model(Tasks) as a high chart. The code is here.
public static Result format(){
return ok(views.html.frmt.render("Visualize it",Task.all()));
}
This goes to this view page.
http://ideone.com/ycz9ko
Currently, I use scala templating inside the javascript code itself. Refer to lines 9-14 and lines 20-24.This unelegant style of doing things is not really optimal.
I want to be able to accomplish the above using Json instead.
public static Result jsonIt(){
List<Task> tasks = Task.all();
return ok(Json.toJson(tasks));
}
My Qns are how to send the JSON objects to a view template.
And how to parse it into a Highcharts format. Is there some standard procedure to do this ? Or else I have to write my own method to do this ?
It'll great if someone can show me a code snippet. Also I would prefer a post not using Ajax. I would just want to know how to do this first.
I also found this stackoverflow post useful.how to parse json into highcharts. However, it didnt answer the part about converting from Play format to Highcharts format.
Thanks in advance

You don't need to pass a json object to your template, instead you might do an ajax call from your client side javascript (your template) and get json response that you could use futher in javascript code to build a chart. For example :
You have some path that is bind to your controller jsonIt() like so /chartsdata/json
then using jquery shorthand for ajax request:
var chart_data = $.get('/chartsdata/json', function(data) {
return data;
});
now you can use a chart_data that is an array of objects where each object represents a Task, in your further javascript code to build a chart.

Related

JSON serialisers and alternative http responses with Django

I'm trying to create a filter system on a click event - using an AJAX post method to update the context that is shown on the template.
I'm currently using:
return HttpResponse(json.dumps(context), content_type="application/json")
To return a response with a context object. However, this doesn't quite work with certain object types:
TypeError: is not JSON serializable
I know there's something regarding serialisers but I'm currently unable to either a.) use them correctly or b.) use them at all.
For some context I'm passing filter variables to the view with the AJAX post method - then:
posts = Post.published.filter(category__name__in=category_filter_items)
And adding this to my context:
context['posts'] = posts
Would anyone know the correct way to update the context is such a manner?
First of all, you should know that once the Django template is rendered, you can't dynamically modify its context without rendering it again. See template documentation.
Before modifying dynamically your template, you should really consider a way to filter your data by calling a view that renders the template again with the context you need.
Option 1: Render the template again
def my_view(request):
posts = Posts.objects.all()
# TODO: Filter the posts against the request
template = loader.get_template('template.html')
context = {
'posts': posts,
}
return HttpResponse(template.render(context, request))
Option 2: Modify your template dynamically
If you're sure that modifying your template dynamically is your best / only choice, you've got different ways to achieve this.
One of them is changing your template via jQuery, loading a subtemplate that is rendered by your filtering view. Take a look at this issue.
Another way is to get your filtered data via a JSON Api and make sure your template is updated accordingly. You may want to use Angular for instance, which uses a MVVM architecture pattern.
How to serialize models in Django?
Django provides serialization of models as a core feature.
Serializing your models to JSON is as simple as:
from django.core.serializers import serialize
serialize('json', SomeModel.objects.all())
If you need to implement an API with serialization of models AND filtering, you may want to use django-rest-framework.
What about use JsonResponse instead of HttpResponse? also you need to define a serializer for Post model.

Angular and JSON, having trouble parsing for ng-repeat

I'm horribly sorry if there is a post for this, I tried to search but didn't find a answer.
Problem:
I'm calling a web service and receiving not so well formed JSON data from a Dynamics Nav service:
JSON:
"[{\"type\":\"2\",\"number\":\"VHT3866\",\"location\":\"Delta\",\"destinationNo\":\"\",\"contactName\":\"Jesus\",\"shipToName\":\"Lord jesus\",\"highPriority\":\"false\",\"hasComment\":\"true\",\"assignedTo\":\"\",\"source\":\"\"},{\"type\":\"2\",\"number\":\"VHT3866\",\"location\":\"Delta\",\"destinationNo\":\"\",\"contactName\":\"Jesus\",\"shipToName\":\"Lord jesus\",\"highPriority\":\"false\",\"hasComment\":\"true\",\"assignedTo\":\"\",\"source\":\"\"}]"
I then take this JSON and use angular.fromJson(json) to get it properly.
It doesn't seem to change into an array of javascript objects, but just plain text.
However if I take the same JSON and just put it manually in like this:
var json = angular.fromJson(stringfromserver);
It turns into a proper javascript object and ng-repeat throws no error.
I found an answer on Quora:
--- Le Batoure,
Angular from json is now strict so assuming that this string is from a trusted source you would have to use "eval()" plus surround the call in parenthesis for it to work
var hatsData = angular.fromJson(eval("(" + hats + ")"))
If you bring your JSON from http request for example you don't need to use the fromJson method.
The JSON is automatically parsed by Angular and you can use it directly.

Highcharts get additional info in tool tip form JSON object

In Angularjs framework I am using Highcharts to populate bubble chart with JSON object. In tool tip I need to add additional data from JSON object.
I have tried with the formatter function but unable to add additional data from JSON Object.
following is a Plunker link for my issue.
Plunker Example
In the example there is a categories called Cables,
Wallplates & Boxes,
Media Distribution when you click on these category the chart will appear.
The problem is that you return string and use json.parse, which doesn't allow to use functions inside JSON. But you can use workaround. In returned json, reference any string in formatter, but in app.js define formatter function and reference this function after json.parse. It will be clear if you take look at the updated example:
http://plnkr.co/edit/LfGd4N6sC0Q2tHwpPxEx?p=preview

Laravel return json or view

I'm developing an API where if the user specifies the action with .json as a suffix (e.g. admin/users.json), they get the response in the return of json, otherwise they get a regular html View.
Some actions may not have a json response, in which case they would just return a html View.
Does anyone have advice on how this can be implemented cleanly? I was hoping it could be achieved via the routing.
I suggest you to create your application as an api.
Foreach page, you need two controllers. Each controller use a different route (in your case, one route ending by .json, and one without).
The json controller return data in json form. The "normal" controller call the corresponding json route, deserialize the json, then pass the resulting array to the view.
This way, you've got a standardized api (and maintained, because your own app use it) available, as well as a "normal" website.
More information:
Consuming my own Laravel API
Edit: Maybe it's doable with a filter, but I'm not sure about that and I don't have time to try it myself right now.
In Laravel 5.x, to implement both capabilities like sending data for AJAX or JSON request and otherwise returning view template for others, all you have to do is check $request->ajax() or $request->isJson().
public function controllerMethod(Request $request)
{
if ($request->ajax() || $request->isJson()) {
//Get data from your Model or whatever
return $data;
} else {
return view('myView.index');
}
}

Rendering Views as String with Spring MVC and Apache Tiles

I am trying to reuse some of my tiles in a controller which is returning a json response to the client. I would like to return a json response similar to the following format:
{
'success': <true or false>,
'response': <the contents of an apache tile>
}
In my controller I would like to perform logic similar to this pseudocode:
boolean valid = validator.validate(modelObj)
String response = ""
if(valid){
response = successView.render() // im looking for a way to actually accomplish
// this, where the successView is the apache tiles view.
// I would also need to pass a model map to the view somehow.
}else{
response = errorView.render()
}
writeJsonResponse(httpResponse, /* a Map whose json representation looks like the one I described above. */)
I belive that you want to implement a view class that will wrap the output of a jsp in json. The class in question may be org.springframework.web.servlet.view.tiles2.TilesView.
Another option may be to extend the JSON converter. org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
If you need to render the view using Apache Tiles 2, you must use
org.springframework.web.servlet.view.tiles2.TilesViewResolver
See the example tutorial here: http://krams915.blogspot.com/2010/12/spring-mvc-3-tiles-2-integration.html
If you need to render the response as JSON, you can use the #ResponseBody which requires Jackson in your classpath. See the example here http://krams915.blogspot.com/2011/01/spring-mvc-3-and-jquery-integration.html (The controller returns JSON). You can also see a similar example of the #ResponseBody at http://krams915.blogspot.com/2010/12/jqgrid-and-spring-3-mvc-integration.html