I'm new to grails. I'm trying to develop a simple page with just a dropdown that when the user makes a selection an AJAX call is made to the database. Thing is that there is are no domain files at all in my application. I only have controllers and views and I intend to keep it this way. So I basically want to use grails to issue a mySQL Select statement through AJAX and get the results.
You could do the below:
From the AJAX call (I prefer jQuery), make the call to the controller action method.
In the controller's method you can use Groovy SQL to execute your query.
Return the result as JSON object and display it whatever way you want it to.
See http://groovy.codehaus.org/Tutorial+6+-+Groovy+SQL for a tutorial on executing SQL using the built-in Groovy SQL library. You can then create a controller action and map your resultset to JSON, and you won't even need a GSP view file. Here's an example Controller class that will do basically what you need.
import groovy.sql.Sql
class MyController {
def sessionFactory
def myAction() {
def sql = new Sql(sessionFactory.currentSession.connection())
sql.execute("select ....") //execute SQL using Groovy SQL
render(contentType:"application/json") {
//render your DB query results as JSON
//you could also use JsonBuilder to render JSON output
}
}
}
Related
Using yii2-httpclient, what is the correct way to access the corresponding yii\httpclient\Request instance from the resulting yii\httpclient\Response object?
I am trying to write a custom XML parser which needs to know what URL it is parsing. It does not seem to be possible to access the original Request (through which I could get the URL) from a parser instance (only the Response).
I have considered utilizing yii\httpclient\Client::EVENT_AFTER_SEND to copy the request into a variable, but that would not be thread-safe, so I need a better solution.
If your parser needs to know URL of request to parse response, it is probably not a parser and you're overusing parser API and ParserInterface. I suggest to create some component which will wrap and hide all request-response-parser logic. Then you will be able to implement custom parser and call it manually:
public function get($url) {
$client = new Client();
$response = $client->createRequest()
->setUrl($url)
->send();
return (new MyParser($url, $response))->getContent();
}
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.
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.
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');
}
}
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