Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery XHR which results in a dom change that persists through refreshes, etc

This is more of a design question than technical, but it has me completely stumped.

So, I have a webpage (hosted via google app engine) that lists a number of seperate forms (each is a question/puzzle). A single puzzle has a number of text boxes to fill out, as well as a submit button. Upon hitting submit, an ajax request is made to the server (running python) which checks if the answers given were correct. In response, the page updates by adding appropriate ticks and crosses by the relevant text boxes, as well as a medium-opacity overlay that covers the entire question (to give the whole thing a "greyed out" effect).

When the page is refreshed, these modifications obviously disappear. However, the ajax request saves the answer info to the database. The questions themselves are created by rendering the page using Jinja2.

So, all the relevant data is saved so that the next time the user returns to the page, questions he has answered in the past are still greyed out, his answers and tick/crosses still there. However, I can't figure out what the best way to do this would be. Do I hard-code the dom modifications for finished questions using if statements in the jinja2 loop (eg:for each question being created, if it's already been answered then render it differently). Or, would it be better to let the page load normally, and then perform an on-load XHR for each question/form on the page?

Really what I want to do is, as each form is rendered in Jinja2, perform an xhr to see if it has an answer in the db, and if so act accordingly. But mixing jinja2 with ajax seems quite messy, surely there is a better way to go about this?

Sorry for the long convoluted question, hopefully it's at least comprehensible.

like image 492
Cerzi Avatar asked Nov 14 '22 19:11

Cerzi


1 Answers

I'd opt for a variant of option #1 (use Jinja2 to render the proper markup) - unless you are rendering a very large number of forms, the page should return in very short order (and if you do have a very large number of forms, making a great number of XHR requests is not going to be faster). Also, by letting Jinja render your HTML you ensure that users without JavaScript can at least see their previous answers (rather than forcing everyone who hits your app to have JavaScript enabled.)

You'll want two things (if you don't already have them):

  1. A way of representing your forms / questions - you'll probably find a class works best for the kind of encapsulation you need.

  2. A way of rendering instances of this class to HTML. This is exactly the sort of thing that macros were designed for. Alternately, you could give your class an __html__ method, (remember to return an instance of Markup).

like image 131
Sean Vieira Avatar answered Dec 18 '22 11:12

Sean Vieira