Ajax-ish updating of a canvas element - javascript

Ok this is more of general technology/approach question.
We have a very simple web 'app' which is basically just a canvas element. We're using javascript to draw a 'fancy UI' on the canvas. We register a mouseclick event, get the coordinates and then try to figure out what widget they clicked on.
My question is, what technology or framework would be best for doing this in an AJAX-ish sort of way? I want the page to render, then user the user clicks somewhere on the canvas, and we pass that coordinate back to some server-side code(PHP or Ruby) which will run some logic, update a database etc., and then come back with new data for the javascript Draw method, effectively updating the UI based on what the user selected, all with a minimum of blinking and refreshing.(although the canvas can be in an IFRAME)
What's the easiest approach to this? I've looked a little at Rails, but it seems like overkill. All I want is to pass back the click coordinates, run some server-side code, and come back with a new chunk of text to pass my javascript Draw function(the one that draws on the canvas element)
EDIT: ok, to be more precise, I'm essentially asking about the easiest way to post back simple string data via AJAX(meaning no full page refresh), and receive a string return value, and update a canvas tag with that return value. I'm not asking for code or an example(although I wouldn't complain) I'm just asking for thoughts on the easiest tech to use - jQuery, Prototype, Rails, JSON vs. XML, etc. The back end is all PHP or Ruby, so I dont need help there, just with the AJAX->Canvas portion of it.

Umm, I suggest Ajax. Its very Ajax-ish.
Okay, let me elaborate - that last line isn't very helpful, but neither is the question. Use JQuery/Prototype to make an ajax request to your service with the co-ordinate and other information you've gathered from the canvas element. Take the response to update canvas depending on what the original input was.
You question is very non-specific... you cite "an AJAX-ish sort of way"... well, that can mean so many things. To me, why go with something thats ajax-like, when you have the real deal ajax.
"What's the easiest approach to this?
I've looked a little at Rails, but it
seems like overkill. All I want is to
pass back the click coordinates, run
some server-side code, and come back
with a new chunk of text to pass my
javascript Draw function(the one that
draws on the canvas element)"
Yup. We're still talking about Ajax.
Vote me down if you want, but better yet - clarify your question and let us know whether you're talking about how to implement passing data back and fourth, or whether you're looking for cutesy UI
effects...

If all you want to do is do some calculations why not also do it in javascript?
If you need permanence, or are running intensive calculations then any of the following will do.
Easy to deploy Frameworks: *
(That is to say, frameworks that have lots of documentation and tutorials available and are written in what are commonly considered to be easier scripting languages.)
CodeIgniter | CakePHP | Zend
Django
Harder to deploy Frameworks: *
(That is to say, frameworks that have less documentation available (and limited tutorials) or are written in more difficult languages [that is, languages that commonly use more difficult paradigms])
Multiple Lisp Frameworks
C++ Frameworks
Multiple Perl Frameworks
More Java Frameworks than you could ever have time to use
I suggest reading up on them, checking the examples and choosing the one that seems most intuitive. Write one or two examples of things you would like to implement and if it still seems intuitive (or the support and tutorials make it easy) then use it to implement your whole project.
*Please note that this division is completely subjective.

Related

Wrapping Python console/plotting in HTML/CSS/JS

I am looking to build a graphical frontend for some python functionality.
Since I am very proficient in HTML/CSS/JS I decided I might check this out as a possibility.
The main idea is to make it easier to explore data/variables, I am thinking of a datagrid for example.
I was also thinking of creating a GUI for things such as plotting with matplotlib (ie: Choose variable for X axis, choose variable for Y axis, pick a color from a dropdown, ...) in order to cut out some of the tediousness in exploring data with several variables.
I would then probably use something like Node-webkit to make a desktop application out of it if possible (and if not, just keep it as a browser project, perhaps).
Essentially what it would boil down to is kind of creating an IDE for python, specialized for data exploration/plotting and perhaps data manipulation.
An example I found for a web-based python console is repl.it
However I have spent a fair amount of time looking for viable ways to go about this, since sending and receiving data from the python interpreter wouldn't be too hard, but it might get a bit harder for exploring variables or plotting data.
So the question is: Are there any projects or libraries out there to facilitate this kind of functionality, or which provide a good starting point for interacting with Python through JavaScript? Are there any pointers you guys can give me to make the experience for users as seamless as possible?
Thanks!

Should I render this template using JavaScript or the server?

I'm rendering a news feed.
I'm planning to use Backbone.js for my javascript stuff because I'm sick of doing manual DOM binds with JQuery.
So right now I'm looking at 2 options.
When the user loads the page, the "news feed" container is blank. But the page triggers a javascript which renders the items of the news feed onto the screen. This would tie into Backbone's models and collections, etc.
When the user loads the page, the "news feed" is rendered by the server. Even if javascript was turned off, the items would still show because the server rendered it via a templating engine.
I want to use Backbone.js to keep my javascript clean. So, I should pick #1, right?? But #1 is much more complicated than #2.
By the way, the reason I'm asking this question is because I don't want to use the routing feature of Backbone.js. I would load each page individually, and use Backbone for the individual items of the page. In other words, I'm using Backbone.js halfway.
If I were to use the routing feature of Backbone.js, then the obvious answer would be #1, right? But I'm afraid it would take too much time to build the route system, and time should be balanced into my equation as well.
I'm sorry if this question is confusing: I just want to know the best practice of using Backbone.js and saving time as well.
There are advantages and disadvantages to both, so I would say this: choose the option that is best for you, according to your requirements.
I don't know Backbone.js, so I'm going to keep my answer to client- versus server-side rendering.
Client-side Rendering
This approach allows you to render your structure quickly on the server-side, then let the user's JavaScript pick up the actual content.
Pros:
Quicker perceived user experience: if there's enough static content on the initial render, then the user gets their page back (or at least the beginning of it) quicker and they won't be bothered about the dynamic content, because in all likelihood that will render reasonably quickly too.
Better control of caching: By requiring that the browser makes multiple requests, you can set up your server to use different caching headers for each URL, depending on your requirements. In this way, you could allow users to cache the initial page render, but require that a user fetch dynamic (changing) content every time.
Cons:
User must have JavaScript enabled: This is an obvious one and I shouldn't even need to mention it, but you are cutting out a (very small) portion of your user base if you don't provide a graceful alternative to your JS-heavy site.
Complexity: This one is a little subjective, but in some ways it's just simpler to have everything in your server-side language and not require so much back-and-forth. Of course, it can go both ways.
Slow post-processing: This depends on the browser, but the fact is that if a lot of DOM manipulation or other post-processing needs to occur after retrieving the dynamic content, it might be faster to let the server do it if the server is underutilized. Most browsers are good at basic DOM manipulation, but if you have to do JSON parsing, sorting, arithmetic, etc., some of that might be faster on the server.
Server-side Rendering
This approach allows the user to receive everything at once and also caters to browsers that don't have good JavaScript support, but it also means everything takes a bit longer before the browser gets the first <html> tag.
Pros:
Content appears all at once: If your server is fast, it will render everything all at once, and that's that. No messy XmlHttpRequests (does anyone still use those directly?).
Quick post-processing: Just like you wouldn't want your application layer to do sorting of a database queryset because the database is faster, you might also want to reserve a good amount of processing on the server-side. If you design for the client-side approach, it's easy to get carried away and put the processing in the wrong place.
Cons:
Slower perceived user experience: A user won't be able to see a single byte until the server's work is all done. Sure, the server is probably going to zip through it, but it's still a few extra seconds on the user's side and you would do them a favor by rendering what you can right away.
Does not scale as well because server spends more time on requests: It might be that you really want the server to finish a request quickly and move on to the next connection.
Which of these are most important to your requirements? That should inform your decision.
I don't know backbone, but here's a simple thought: if at all possible and secure, do everything on the client instead of the server. That way the server has less work to do and can therefore handle more connections and scale better.
But #1 is much more complicated than #2.
Not really. Once you get your hang of Backbone and jQuery and client-side templating (and maybe throw CoffeeScript into the mix, too), then this is not really difficult. In fact, it greatly simplifies your server code, as all the display-related functions are now removed. You could also even have different clients (mobile version, for example) running against the same server.
Even if javascript was turned off, the items would still show because the server rendered it via a templating engine.
That is the important consideration here. If you want to support users without Javascript, then you need a non-JS version.
If you already have a non-JS version, you can think about if you still need the "enhanced" version, and if you do, if you want to re-use the server-side templating you already have coded and tested and need to maintain anyway, or duplicate the effort client-side, which adds development cost, but as you say may provide a superior experience and lower the load on the server (although I cannot imagine that fetching rendered data versus fetching XML data makes that much of a difference).
If you do not need to support users without Javascript, then by all means, render on the client.
I think Backbone's aim is to organize a Javascript in-page client application. But first of all you should take a position on the next statement:
Even if javascript was turned off, the web-app still works in "post-back mode".
Is that one of your requirements? (This is not a simple requirement.) If no, then I'll advice you: "Do more JS". But if yes then I believe your best friend is jQuery load function.
A Note: I'm a Java programmer and there's a lot of server-side frameworks that bring the ability to write applications that work ajax-ly when js is enabled and switch on post-backs when it isn't. I think Wicket and Echo2 are two of them but it's meant they are server-side libraries...

How to organize the code for a javascript UI widget?

The web app I'm working on has several fairly complex and stateful pieces of client-side UI. I'm trying to keep things sane by organizing them into composable javascript widgets. Some of the requirements are:
1) Some of the data required to initialize the widget needs to come from the server
2) Some of the data comes from the client (based on which of a list of items is selected)
3) The state of some sections of the widget needs to be remembered when it's closed and reopened
4) The state of other sections needs to be forgotten and reset to the original setting
5) The page has to fully render very quickly, so AJAX calls need to be minimized
So, my question is, how do you organize the code for this widget? What I have currently involves sending down the HTML for the widget with some data (i.e. #1) filled in on the server side (to avoid sending down the data via an extra AJAX call). I then have a bunch of jquery code that fills in the client side stuff in an ad-hoc fashion. And then more code to reset everything back to the desired state on the second invocation. Surely there's a more declarative way to accomplish this?
I think you would be very happy using Javascript MVC. It makes it much easier to manage the state of components, and makes it pretty easy to manage data on the client side instead of making repeated ajax calls. Do the tutorial and I think you will be quite happy.
EDIT
My original answer doesn't address the page rendering speed.
If you are really worried about page rendering speed, the best solution is to render the document. The next best solution is to not worry about the problem until the final stages of development. It is pretty easy to optimize data loading behavior, and you will come up with much better solution after you have solidified the rest of your application design.
I have employed various techniques to improve render performance, such as cachable ajax, or injecting script blocks with data when the page is generated on the server. Both of these approaches have given me significant performance boosts, and both were easily applied at later stages in development.
If you're going to roll your own widget, and you're going to persist the state of the widget, then assign each widget a GUID/UUID and use that as part of the "container name" of the widget (I take the last 13 digits for mine to ensure some sort of randomness. I don't maintain that it won't ever break.) You can do that part easily enough during object creation, either serverside or clientside. You can persist the GUID/UUID as the ID of the widget as well, so that isn't likely to ever change.
All this was given as part of "how do I compose the widget" for modularity sake, especially during javascript operation (the italicized section is what I thought was meant... further conversation leads me to believe that I may have been wrong. leaving it for posterity now)
Otherwise, see the comments above.

Thinking of new way of building a db page populating data via api calls - are there any issues doing it this way

Up to know, for DB driven web sites, I've used php (and CodeIgniter) to populate the data within the page prior to rendering, what I'm thinking about doing now is to develop a javascript (via jquery) page, make it as interactive as possible and then connect to the db through ajax/json calls - so NO data populated to the screen prior to rendering.
WHY? sort of an idea that I can, some day, hook the same web page to different data sources - a true separation of page from data - linking only via ajax.
I think the biggest issue could be performance...are there other things to watch out for? What's the best approach to handling security (stateless/sessionless)?
The biggest question is accessibility. What about those people using screenreaders, for which Javascript doesn't work? What about those on mobile phones (non-smartphones), again with very limited or no Javascript functionality? What about those people who have simply disabled JS? Event these days, you simply can't assume that everyone can use JS.
I like the original idea, but perhaps this would be better done via a simple server-side wrapper, which calls out to your data source but which can be quickly and easily changed to point at a different one.
Definitely something I've considered doing but you'd probably want to develop some kind of framework (or see if someone already has) if you're going to do this. Brute forcing this kind of thing will lead to a lot of redundant code and unnecessary hair loss. Perhaps a jQuery plugin? I'd be very interested to see what you came up with.

Is there a way to manipulate code generated by Processing.js via Javascript?

I would like to call some functions or alter some variables after the Processing.js code has been parsed. Right now the only way to do this is to manipulate the source code, and then reload the source into Processing.
I am beginning to suspect that there is no straight answer to that question at present. For the time being, I am doing as you do. I am using the Django web framework. I have Django write every line of Processing.js code to the page through its template handler. Django is first writing the HTML script element, then Processing.js assignment statements defining the sketch parameters, then the body code for the sketch, then Processing.js library functions and classes as a particular sketch requires, then the closing script tag. I’m looping through multiple sketches and finish up with a looping initialization routine.
With this scheme I have fine control over the HTML as Django’s template handler lets me control id’s and classes for the div elements that contain the sketches as well as the canvas elements. This amounts to crude dynamic behavior; every time the user POSTs a form the sketches are updated. Python is reading a lot of files, each containing a lot of bits, and those bits pass through several hands on their way to the browser, which must slow thing up as compared with a simple update of the data.
I'm intrigued at the possibility of genuine client-side dynamic behavior using forms mediated by, perhaps, jQuery. See this fascinating post at Design Intellection by David Yeiser. So, jQuery can talk to Processing.js, which is amazing, but not too surprising, as they are both JavaScript. I'm no expert, but I think some global namespace abuse occurs with this technique. Speaking of global namespace abuse, check out these two posts at Irrational Exuberance, "Updating Processing.js Graphics via Ajax," and "Using Javascript to Control Processing." If you can do it with PHP, you can do it with the flavor of your choice.
Apparently, Processing.js has an "internal" AJAX function that might be of use to you. See this cached post, courtesy Google. Compare with the current radically edited version, changed just a few days ago. So, the Processing.js collaborators have got the task of loading a sketch and associating it with a canvas down to two lines of code, but the more general task of loading assorted bits and pieces, including variable data, is getting no air time. Perhaps they're rewriting the whole AJAX thing. I would like to know if the p.ajax function could be used to load and concatenate a number of Processing.js assets, like data assignments, setup(), draw() and functions and classes in a flexible way forming a complete sketch.
My CS son says I could re-write my Processing.js code using the JavaScript native API and then it would be pure JavaScript, and could be loaded using a normal script tag and not with type="application/processing". He thinks I would have more flexibility plus the option to use minimization/obfuscation. Here is an example using JSON at ProDevTips. JSON is pretty convenient to use with Django. I've seen the API here and there on the web. It looks straightforward, but I don't know if it's documented anywhere. You could just pick through source at Github. Otherwise, I like this approach.
So, I don't have a succinct answer, but I suspect the situation is evolving quickly. One last possibility is the use of XHR. See this StackOverflow post and the link to the downloadable file at the Hyper-Metrix website. A notable Processing.js whiz by the name of Alistair MacDonald (F1LT3R) has published an number of approaches to initializing Processing.js sketches. He would probably know as well as anyone how to do what we want done.
I would be overjoyed if a well-informed person (i.e. a Processing.js insider) would address this issue.

Categories