Where to create html? Server or client side? - ajax

I am using dajax for ajax in my django app.
After getting some data from database I create list of <li> elements in my python ajax.py and assign it with dajax to inner html of some container. Like this:
#dajaxice_register
def get_transactions(request):
dajax = Dajax()
transactions = get_transactions()
dajax.assign('#transactions', 'innerHTML', ''.join(transactions))
return dajax.json()
What is considered best practice? Returning html from server or returning json and then creating html in script?

I would return JSON from the server and bind that to the DOM using JavaScript. That way you're keeping concerns separate, and also returning the minimum amount of data from the server.

Always returning JSON helps to create a services oriented architecture with a good separation between your view and your controller (and model).
With this approach, you can have a pure-HTML UI and a REST API to retrieve datas from server.
I think it's a good practice, but it's probably better for Web Application and not for generic websites.

Related

Dynamically add form to formset in Django and submit with AJAX

I have read a lot of answers relating to how to dynamically add forms to an model formset in Django and can successfully implement that. However, I would now like to submit the formset with AJAX. This is mostly working now but I have an issue that I can't find a solution to in any other answer:
If you dynamically add a form to the formset, you give it a new form id number that is one larger than the maximum the form currently has and you also increment the management TOTAL_FORMS count by one. The newly added form then saves successfully as a new object.
I am trying to submit by AJAX so the user can continue editing without having the page refresh. The formset saves fine but any dynamically added forms are now existing objects. To account for this I need to increment the INITIAL_FORMS count on the management form when the save is successful. Easy enough. However, I've also realised I need to give the newly created objects an ID since they now exist in the database.
How can I get my view to tell me the ID of the new objects in its response to the AJAX call? Or is there a better way of looking at this?
Django forms and formsets are intended for classic browser-based posting of data. Though they can definitely be made to work with Javascript, the more you want to part from the normal behavior, the more complex it gets.
Depending on your requirements, you might start thinking about dropping it and switch to Javascript + REST endpoint. Of course, if you need progressive enhancements and you are required to have it work without javascript, that's not an option.
In any case, you want to have a customized view for posting from JS, so that you can get the result back and parse it easily in your AJAX handler. Probably some JSON.
There are several approaches you could take.
Have your AJAX send data to a different URL. This is pertinent if you have an API or are planning to build one at some point. So your form, when submitted normally, will do its old-style processing but your AJAX will talk to the API endpoint instead.
For instance, your form send to https://example.com/myform, but your Javascript code talks to REST api at https://example.com/api/v1/mymodel/ (sending PUT, POST and DELETE requests as appropriate).
Or if you don't have an API and building one seems overkill, you may just alter your view so it formats its output differently depending on whether the data is being submitted in the regular way or using AJAX.
You'd go about it like this:
class MyFormView(.....):
def render_to_response(self, context, **kwargs):
if self.request.is_ajax():
return self.render_to_json(context, **kwargs)
return super().render_to_response(context, **kwargs)
def render_to_json(context, **kwargs):
data = {
# see below!
}
return HttpResponse(
content=json.dumps(data).encode('ascii'),
content_type='application/json',
)
This is just an outline. You need to ensure is_ajax will detect it properly (see django doc). And you need to properly build data from context: extract the things you want to send back to your JS code and put them in the dict.
You will find it's manageable if you just do this for one, maybe two views in your project, but very quickly you'll want to have a small API instead, especially given how easy it is to build one with packages such as Django REST framework.
In your view, where you save the object, AFTER the save, the object.id will contain the new id for the object, which you can return via json or however you want in your ajax response, and then yes you will need to fill that into the formset row so that it will be submitted the next time.
One thing you have to watch out for is that django expects all existing rows to be at the top of the formset, and any new rows to be at the bottom. Otherwise, the formset save will complain about missing id's. So if you're doing any kind of sorting in your javascript, you can't do that.. unless you do quite a bit of fixing of all the field names etc in the formset. The formset code uses the numbers in the management form to determine which rows to insert and which rows to update, it does not do it on the basis of whether or not an id is present. Unfortunately...

Node, Express, Ajax, and Jade Example

I'm looking for a simple example of a Node/Express/Jade page being updated using an Ajax call with both the client and server side code.
I'm having a bit of trouble putting it all together in my head.
There are great many ways this could be done and it's not immediately apparent which approach you want to take.
I suppose the simplest scenario would be to add some client-side logic to fetch pieces of html from the server and update the client. This is easily achieved using jQuery (put it inside a document ready block to wire up the event):
$('#button').click(function() {
$.get('/some/url', {foo: 42}, function(result) {
$('#target').html(result);
}
}
This way all your html is generated on the server and you simply fetch and insert it into the page as needed.
You could also fetch json from the server and render the html on the client, but that is one of the alternative approaches. I highly recommend giving TodoMVC a look - it's a todo-list application with many different implementations (each using a different framework) and therefore a great learning resource for the various approaches and helper libraries.
I'd also recommend the Hands-on Node.js book. It will help you understand routing and how to get started with Node.

CakePHP and reusable approach

I would develop my CakePHP application in the most reusable way. I'd like to treat it as webservices, so I don't want to strictly bind controller with view. My idea is: controller just returns json info, the view calls the controller and get the json and make html output.
How can I realize that? Could be a good approch, developing pages rather than views, and inside that pages call the webservices previously developed.
You can even forget about creating view files, using $this->set('_serialize', array('people')); in your PeopleController::show()
Well Cake is kinda' works like this "out of the box". You can use Router::parseExtensions(); to define what type of data you would like to serve. For example in app/Config/routes.php:
Router::parseExtensions('xml','json');
This will make it possible to detect what kind of request is incoming. For example if someone requests:
www.example.com/people/list.json or www.example.com/people/list.xml, in your PeopleController's list() method you'd be able to detect what kind of resource is being requested - json or xml, or of course any other
extension you define. This is what the RequestHandlerComponent is used for. You can check if it is xml for example:
if($this->RequestHandler->isXml()) {
//Some code
}
The different extensions are only different representation of the data, so it shouldn't matter what exactly you're serving. From v2.1 Cake will automatically switch the view class when it sees a JSON or XML request, which takes us to the new JSON and XML views.
All you will have to do is provide the views in the appropriate places.
In View/People (as for this example) you would have:
..View/People/
list.ctp
xml/
list.ctp - XML view
json/
list.ctp - JSON view

use ajax to fetch data from java hashtable in jsp page

I'm working on a project that the web page will fetch the data from java hashtable object in jsp page. I'm using a jsp for gerenated the web page based on HTML. The data is stored in the java hasbtable object on the server. I want to try to make an AJAX call to fetch the data from the server, then display it in the jsp page.
I just want to know if this is possible to do that by make an AJAX call to access the java hashtable object, then fetch the data back to the client side.
Thanks
Here is the test.jsp page which contain the hashtable obejcts:
Hashtable generalTable = (Hashtable) metaDataTable.get("General");
Hashtable adminTable = (Hashtable) metaDataTable.get("Administration");
My inital approach is to make an AJAX call to this test.jsp page. Then try to access those two GeneralTable and adminTable hashtable objects. In those two obejcts, it contains the values I would like to fetch.
Unfortunately, I don't have the code yet for my part because I don't know if this is possible or not.
Yes, it's possible, but you will need to have some server-side code to deal wit the request for the data you want, just like with any other AJAX functionality in any other system.
One way to do this would be to have a "special" jsp that gives you back the data you need without any of the typical HTML. Having the special jsp output it's data as a JSON object will make your life much easier in the client-side code.

Django client side query construction

I'm making a pretty standard AJAXy (well, no XML actually) web page. The browser makes a bunch of API queries that return JSON to run the site. The problem is, I need to add to the API interface each time the page needs to do something new. The new API interface is usually little more than a database query followed by mapping the returned objects to JSON.
What I'd like to do is to get rid of all that server-side duplication and just have the page make database requests itself (using the model interface), but in a way that is safe (i.e. just read only ones). I think this would amount to an interface for constructing Q objects using JSON or something like that, and then send that up to the server, run the query, and return the results. Before I go making my own half-broken architecture for this, I'm wondering if this has already been done well. Also, is this even the best way to go about eliminating this duplication?
Thanks
Search multiple fields of django model without 3rd party app
Django SQL OR via filter() & Q(): Dynamic?
Generate a django queryset based on dict keys
Just replace with operator.and_ where appropriate.

Resources