Ajax applications with perl backend - how to? - javascript

There are already questions about the Perl+AJAX, like here, here or here and several others. They're more than 2 years old and I was hoping for some new stuff.
The questions are:
What is the most preferred method today making AJAX apps with a Perl backend?
Are there some active and commonly used Perl modules that help build AJAX based applications?
Something, for the usual workflow:
if clicked this button (or changed this field.. etc),
POST these data to the server,
read the JSON answer,
and update this/these DIV(s) in a DOM... etc.
This question is can be classified as vague, but I'm really lost and need help with this: what is the most common way making AJAX apps in the Perl world, TODAY.
Looking for a helper module that help me build the browser-side javascript.
I found these:
https://metacpan.org/pod/OpenThought
https://metacpan.org/pod/HTML::AjaxTags
https://metacpan.org/pod/CGI::Ajax (but this is CGI based and IMHO not the best for Plack world)
These modules have not been updated for several years. Are they stable and in use? Or are they deprecated and is there some better way? (for the modern Perl technologies - like Plack).
UPDATE
As I read answers, I'm thinking that the main problem is probably in my English. I don't know how to express myself right.
I know Perl. Maybe I'm not an expert, but I wrote several thousand lines of code. I know Dancer, and already write some apps in Mojo...::Lite. Know JSON{::XS} and I know how AJAX works.
Now (for some reason) I prefer using Mason2, with Mason::Plugin::RouterSimple and several other CPAN modules and Moose. Catalyst, Jifty are too big for my needs.
Back to the question:
My favorite JS framework is jQuery, I'm using it in several projects for modal windows, or accordions, tabs etc.
BUT
My main problem is exactly in Sismetic's answer. I don't want to write JavaScript. Don't like it. (Don't know it very well, and hate every language where I must write something like: var arr = new Array(); instead of my #arr)
So, looking for a solution, how I can minimize (or in the ideal world - totally eliminate) the need of writing the JavaScript code. Don't want write into my templates
$('.clickableButton').click(function(e) {
.... etc... etc..
)}
but something like:
$ajax->make_button( -onchange=>$url, -updatedom=>'#thisdiv", some_special_button_description_in_perl );
$tohead .= $ajax->gen_libs();
$tohtml .= $ajax->gen_html();
$jsdocready .= $ajax->gen_jsinitcode();
An in my templates will output only $tohead in the head part (so include jQuery), $tohtml will come into body, and $jsdocready will come into the end of body as JavaScript init code.
Offcourse, the above is an very stupid example, but hopefully shows what I mean. Simply: The ideal solution was (probably does not exists) is totally eliminate the need writing JavaScript, only Perl code what will generate the needed JS.
Therefore I mentioned the above modules, especially https://metacpan.org/pod/OpenThought, because these really help minimize writing JavaScript. The problem is - these have not updated for 2 years. ;( And unfortunately - I don't know any others.

The reason you're not getting answers isn't just the vagueness of the question. The problem space is very wide and has a many angles of attack.
Let's clarify that the "x" in Ajax shouldn't be taken to mean XML anymore. JSON is obviously more natural and doesn't suffer from nearly as many problems so all my advice will point toward it.
What hobbs said already is right on. You do not want to mess with the server-side code much at all but adopt a framework. This is not because dealing with Ajax is hard in Perl; it's trivial. It's because the problem space gets messy quickly and you'll end up repeating your code in endless minor variations. So–
Perl/Server-side
Any of these will make you happy eventually. They all have a learning curve. There are other options but these are the Best™.
Catalyst (Catalyst::View::JSON)
Dancer (Dancer::Serializer::JSON)
Mojolicious (prefer Mojolicious for HTML5/Websockets)
Deployment SHOULD be Plack/PSGI based.
Take the time to really learn the core of Perl's Ajax handling: JSON(::XS) so you know what the views in the various frameworks do under the covers.
JavaScript/Client-side
This is essentially an embarrassment of riches at this point.
jQuery
Many Perl hackers like this kit; it seems to hit the same sweet spot Perl does. I adore jQuery.
Dojo
I'm not a fan — they had the worst documentation possible in early versions and broke compatibility while deleting what little docs used to exist — but it's well-liked in its current version.
MochiKit
MooTools
YUI
ExtJS
This, now distant, fork from YUI is the 800lb gorilla of client-side JS. I personally dislike it because of its lack of graceful degradation, et cetera, but it is highly regarded and very sharp looking out of the box.
I personally dislike and can't recommend prototype and though I've never used it I also chose not to put script.aculo.us on the list.
There are plenty of other amazing specialty kits out there too; e.g., Modernizr. When you are looking into JS, consider how important standards compliance and forward-looking features like CSS3, HTML5, extended event handling like multi-touch are to what you'll do. Good luck and have fun.
Update: Possibly of further interest
Jemplate – templating in JavaScript
Catalyst::View::Jemplate
Jifty – YAWF

Looking for "ajax" isn't really what you need. Just use a web framework of your choice that has good facilities for serialization, working with Accept headers, etc. For example Catalyst and Catalyst::Action::REST, or Dancer. Don't write Perl that writes Javascript, it will only make you sad.

I use CGI::Application as my base framework and CGI::Application::Plugin::JSON to return JSON data to jQuery.

If you want to generate HTML code with a Perl module, I would recommend CGI.pm:
...
use strict;
use warnings;
#CGI is shipped along perl, I think
use CGI;
my $CGI = CGI->new();
my $return_string = '';
#From CGI documentation on CPAN
#http://search.cpan.org/~markstos/CGI.pm-3.55/lib/CGI.pm
$return_string .= $CGI->header;
$return_string .= $CGI->start_html('hello world');
$return_string .= $CGI->h1('hello world');
$return_string .= $CGI->button(-name => 'button_name',
-value => 'Click Me!',
#Javascript event if needed
-onClick => "do_something()"
);
$return_string .= $CGI->end_html;
print $return_string;
Or(as I dont like the latter method) you could just write it on perl(generating it yourself manually):
use strict;
use warnings;
#Needed header, otherwise will return error
print "Content-type: text/html\n\n";
#return random number from 0 to 100
my $random_number = int(rand(101));
my $HTML_generated_string = qq|
<html>
<head>
<title>HTML generated manually with perl</title>
</head>
<body>
<h1>Hello world</h1>
Bla bla bla Heres the random number $random_number
</body>
</html>
|;
print $HTML_generated_string;
Other than that, I dont know any extra modules to do it. I normally do it by hand, or write a template(with CGI::Application).

I don't think the thing you are asking for exists. You can't write AJAX apps without using JavaScript. If someone invented a way to do JavaScript without JavaScript it would be a major project and not one person's weekend CPAN module.
I suggest rethinking your view of JavaScript. JavaScript is an excellent language and JQuery is great as well. There is a lot of bad JavaScript code out there, but there is good JavaScript code as well. Just like there are good and bad practices in the Perl community. I'd suggest you keep an open mind and take another look at JavaScript and make sure you really know the foundations well. Sometimes my frustration with a language just means I haven't learned it very well.
There are some very cool things happening in the JavaScript world. I admit its chaotic and decentralized and there is a lot of different stuff to know about and thats exhausting but its also exciting that so much is happening.
You probably already know about these resources, but just in case: FireBug, Mozilla Developer Network JavaScript docs, and JavaScript Garden

See Dancer::Plugin::Ajax on cpan
http://metacpan.org/pod/Dancer::Plugin::Ajax

Related

What JS library can be selected for RIA REST based application

I have ad idea to make some REST application. I already selected what I will use on server side.
But now I have a big big deal, what i should use to make RICH web app ?
I have middle javascript knowledges. I know jquery, I did my own jquery plugin. it should tell you about my level, so far from pro level.
But i would like to try make it by my self. And i'm thinking that jQuery it's not good choice for this kind of task. I would like to have something more flexible, and not looks like a lot of callback for specific events. Something maybe in MVC style.. But i don't want to spend a lot of hour to lear complicated stuff.
For example: ini PHP life there are a lot of frameworks, I choose Yii, it's really more easier to understand and make something, than Symfony (even 2nd version) for instance.
So i'm looking something similar Yii (but for a browser side), something fast, easy to learn, flexible and powerfull.
I thought maybe it could be cofeescript, or cappuccino or something else ...
BUT I don't have so much time to learn and try so many JS frameworks and libraries to make decision by my self, this is why i'm asking you all.
Thanks.
Typically my choice would be:
jQuery - for general stuff
Q promises library for handling of more
complicated asynchronous operations
Backbone for building model on the
client side
Mustache templates for interaction with HTML
Jasmine - for unit testing of the application
However if you plan to make very rich user interface, you need to handle many various events and you don't want to write your own visual controls (since they are complicated) you can go with ExtJS (note the potencial need to buy licence).
For me Jquery ui has always been easy to use with my limited javascript knowledge .The learning curve wasn't steep at all and lots of community plugins helped in the further development as well .
Apart from that you can try Mootools , Extjs (very nice components but requires a bit learning ) and yui (definite learning required for me ) .
I would recommend using jQuery because you already have some knowledge about it. When it comes jQuery UI it offers some functionality: http://jqueryui.com/demos/. Is this functionality RICH enough?
On top of jQuery, you can use several JS libraries to fullfil specific needs:
Charts:
http://www.highcharts.com/
Grid:
http://www.activewidgets.com/
When you are using JS it's really important that you keep your own JS code in good order. Devide your functionality into separate js-files. Think about your object structure. JS is prototypal language (you can inherit directly from other objects).
For me it took some time to find out the way to write good JS code. I highly recommend this book: JavaScript: The Good Parts (by Douglas Crockford).
// Namespace
var MyNameSpace = {};
MyNameSpace.vehicle = function() {
var that = {};
var my = my || {};
my.thisIsMyOwn;
that.publicFunction = function() {
my.thisIsMyOwn = "put something here";
};
return that;
};
MyNameSpace.car = function() {
var that = MyNameSpace.vehicle(); // "inheritance"
return that;
};

Download a file from a site (partly written in Javascript) using Python

I'm trying to use Python to download a voice file (mp3) from this site:
I've tried to use mechanize and twill but I haven't got the proper result. I've heard about selenium as well. Anyway, I don't even know if it makes sense technically (mechanize + Javascript).
I was looking for an answer and finally I've found this solution.
It seems like a similar problem to mine but I have absoutely no idea what should I put instead of the 4th line.
If you have any proposition (maybe completely different to mine) I'll be glad to see it.
(Moving to answer to get more space)
Thanks for pointing me to selenium, I didn't know that and it looks cool; anyways: I had a quick look and the js seems to fire an ajax request, that yields no apparent result -- I guess the audio transfer is done some way in the background via flash or so; anyways: what about using the service they offer: developer.ivona.com instead of trying hacking your webservice out of the demo interface..?
Anyways, here it is the hacked web-service you asked for:
This is the URL you want to GET:
"http://www.ivona.com/voicetest.php?rtr=1&t2r=%(the_text)s..&v2r=dXNfc2FsbGk.&lang=us" % dict(
the_text=base64.b64encode("Hello, world!"),
the_voice=base64.b64encode("us_salli"),
)
You can test that with, for example, mplayer:
mplayer "http://www.ivona.com/voicetest.php?rtr=1&t2r=SGVsbG8sIHdvcmxkIQ==..&v2r=dXNfc2FsbGk.&lang=us"
And, from Python, use urllib to retrieve and store somewhere.
Beware that, since this is an unauthorized use, you might get blocked / incur in legal issues / etc. -- don't use in a production application!

What are the arguments against the inclusion of server side scripting in JavaScript code blocks?

I've been arguing for some time against embedding server-side tags in JavaScript code, but was put on the spot today by a developer who seemed unconvinced
The code in question was a legacy ASP application, although this is largely unimportant as it could equally apply to ASP.NET or PHP (for example).
The example in question revolved around the use of a constant that they had defined in ServerSide code.
'VB
Const MY_CONST: MY_CONST = 1
If sMyVbVar = MY_CONST Then
'Do Something
End If
//JavaScript
if (sMyJsVar === "<%= MY_CONST%>"){
//DoSomething
}
My standard arguments against this are:
Script injection: The server-side tag could include code that can break the JavaScript code
Unit testing. Harder to isolate units of code for testing
Code Separation : We should keep web page technologies apart as much as possible.
The reason for doing this was so that the developer did not have to define the constant in two places. They reasoned that as it was a value that they controlled, that it wasn't subject to script injection. This reduced my justification for (1) to "We're trying to keep the standards simple, and defining exception cases would confuse people"
The unit testing and code separation arguments did not hold water either, as the page itself was a horrible amalgam of HTML, JavaScript, ASP.NET, CSS, XML....you name it, it was there. No code that was every going to be included in this page could possibly be unit tested.
So I found myself feeling like a bit of a pedant insisting that the code was changed, given the circumstances.
Are there any further arguments that might support my reasoning, or am I, in fact being a bit pedantic in this insistence?
Script injection: The server-side tag could include code that can break the JavaScript code
So write the code properly and make sure that values are correctly escaped when introduced into the JavaScript context. If your framework doesn't include a JavaScript "quoter" tool (hint: the JSON support is probably all you need), write one.
Unit testing. Harder to isolate units of code for testing
This is a good point, but if it's necessary for the server to drop things into the page for code to use, then it's necessary. I mean, there are times when this simply has to be done. A good way to do it is for the page to contain some sort of minimal block of data. Thus the server-munged JavaScript on the page really isn't "code" to be tested, it's just data. The real client code included from .js files can find the data and use it.
Thus, the page may contain:
<script>
(function(window) {
window['pageData'] = {
companyName: '<%= company.name %>',
// etc
};
})(this);
</script>
Now your nicely-encapsulated pure JavaScript code in ".js" files just has to check for window.pageData, and it's good to go.
Code Separation : We should keep web page technologies apart as much as possible.
Agreed, but it's simply a fact that sometimes server-side data needs to drive client-side behavior. To create hidden DOM nodes solely for the purpose of storing data and satisfying your rules is itself a pretty ugly practice.
Coding rules and aesthetics are Good Things. However, one should be pragmatic and take everything in perspective. It's important to remember that the context of such rules is not always a Perfect Divine Creation, and in the case of HTML, CSS, and JavaScript I think that fact is glaringly clear. In such an imperfect environment, hard-line rules can force you into unnecessary work and code that's actually harder to maintain.
edit — oh here's something else I just thought of; sort-of a compromise. A "trick" popularized (in part) by the jQuery gang with their "micro template" facility (apologies to the web genius who actually hit upon this first) is to use <script> tags that are sort-of "neutered":
<script id='pageData' type='text/plain'>
{
'companyName': '<%= company.name %>',
'accountType': '<%= user.primaryAccount.type %>',
// etc
}
</script>
Now the browser itself will not even execute that script - the "type" attribute isn't something it understands as being code, so it just ignores it. However, browsers do make the content of such scripts available, so your code can find the script by "id" value and then, via some safe JSON library or a native browser API if available, parse the notation and extract what it needs. The values still have to be properly quoted etc, but you're somewhat safer from XSS holes because it's being parsed as JSON and not as "live" full-blown JavaScript.
The reason for doing this was so that the developer did not have to define the constant in two places.
To me, this is a better argument than any argument you can make against it. It is the DRY principle. And it greatly enhances code maintainability.
Every style guide/rule taken to extreme leads to an anti-pattern. In this case your insistence of separation of technology breaks the DRY principle and can potentially make code harder to maintain. Even DRY itself if taken to extreme can lead to an anti-pattern: softcoding.
Code maintainability is a fine balance. Style guides are there to help maintain that balance. But you have to know when those very guides help and when they themselves become a problem.
Note that in the example you have given the code would not break syntax hilighting or parsing (even stackoverflow hilights it correctly) so the IDE argument would not work since the IDE can still parse that code correctly.
it simply gets unreadable. You have to take a closer look to divide the different languages. If JavaScript and the mixed-in language use the same variable names, things are getting even worse. This is especially hard for people that have to look at others people code.
Many IDEs have problems with syntax highlighting of heavily mixed documents, which can lead to the loss of Auto-Completion, proper Syntax Highlighting and so on.
It makes the code less re-usable. Think of a JavaScript function that does a common task, like echoing an array of things. If you separate the JavaScript-logic from the data it's iterating over, you can use the same function all over your application, and changes to this function have to be done only once. If the data it's iterating over is mixed with the JavaScript output loop you probably end up repeating the JavaScript code just because the mixed in language has an additional if-statement before each loop.

What software/webapp can I use to edit HTML pages?

Ok, my question's not as broad as it seems, to summarize 8 months effort on my part:
I create chunks of re-usable, extensible XHTML which degrades gracefully and is all kinds of awesome. Most of my code chunks are provided a Javascript interaction layer, and are styled with CSS. I set to work pulling my code chunks into Dreamweaver as 'Snippets' but they're unintelligent chunks of text. Also, once inserted, my beautiful code chunks get mangled by the non-techies who are the ones actually using Dreamweaver.
Also, because they're unintelligent snippets, I have a line of Javascript which configures the code chunks when initialised - see this post for further detail on my approach. But currently I have to replicate a single code chunk as many times as there are configuration options (so each 'snippet' may only differ from another of the same type by ONE config value). This is incredibly lame, it works, but its lame and time-consuming for me to re-deploy a bunch of snippets and hard for my team to remember all the variations.
So I have a series of requirements, to my mind, as the most likely things to solve in any system I put my chunks into:
The inserted code is not modified at insertion time, by the system
The code to be inserted needs to allow config options
I'd be overjoyed if, once inserted, the only editable parts are text nodes
Copy and pasting these whole objects
A clean interface from which to choose from my range of code chunks
It's a serious list of requirements I presume, much searching led me to Kompoze and its 'Smart widgets' which, according to a random post from 2004, suggests XUL files can be created and extensions can be made which sounds vaguely like what I want. The text editor itself was less prone to destruction, when compared to Dreamweaver.
So yeah, I've chased too many rabbits on this one, keen as for a solution whether Software+extension, or Webapp.
EDIT:
Btw, it did occur to me to investigate a highly customised TinyMCE instance, but I don't know feasible that is, and unless there's some sweet backend available, I'm stuck with local editing of files for now - not even on a web server...
To my mind the best answer to this question will solve most of the above, and provide some general workflow advice alongside the suggestion(s).
I would go with a solution based around the excellent markItUp! editor. It's very simple to extend it to cope with the requirements you have. You can add sophisticated logic, and it's nice and shiny.
I'd probably combine it with Jeditable for the inline node editing, and build the whole thing on top of Django, for ease and convenience. Completely customisable, surprisingly easy to work with, portable and cross-platform, and easy to set-up for off-line use. Oh, and all free and open-source.
What do you think of this approach:
<div class="thing">
<elements... />
<script type="text/javascript">
document.write('<span id="thing' + thingNo + '"></span>')
new Thing().init({ id:'thing'+thingNo; });
thingNo += 1;
</script>
</div>
Of course, you'll have to change Thing().init so that it would initialize the parent (instead of current) node.
Have you considered server-side includes where the directive is either a generated page or a shell command? E.g.:
<!--#include virtual="./activePage.aspx?withParam1=something&param2=somethingelse" -->
or
<!--#exec cmd="shellCommand -withParams" -->
You can reuse the same page or command, and provide parameters specific to each usage in each XHTML page.

JavaScript code completition done right?

I've tried some of the editors/IDEs regularly recommended for coding JavaScript (Aptana, WebStorm, ...) but none of them has a satisfying autocomplete functionality. I'm probably spoiled by Microsoft's IntelliSense for .NET. There is some JavaScript-IntelliSense in WebDeveloper, but that seems to be a stripped-down version. The best I've found so far is WebStorm, but its code completition is easily distracted by imported libraries (offering hundreds of suggestions) and identical function names.
Did I miss an editor/IDE that uses refactoring (or something else) to offer proper code completition, so that it really "knowns" what that variable-name stands for, I just put a dot behind? Or is something like this on its way?
I always recommend Komodo Edit from ActiveState (now up to version 6, with support for HTML 5 and CSS3 as well as recent versions of Javascript, PHP, etc.) Note that you may have to install addons for the languages you're working in, but you should find them through the Mozilla-like Addon manager.
Also supports jQuery and even lets you use jQuery (along with vanilla Javascript or Python) in its powerful macro IDE.
Code completion example:
<script type="application/x-javascript">
var obj = {};
obj.personnel = [{firstName:"John", lastName:"Brick", age:43},
{firstName:"Jane", lastName:"Motte", age:26}
];
// now type obj. and code completion immediately offers you "personnel"
// note: file must be saved for the app to find all members of declared
// variables, but I save about every 10 seconds so it's not a problem
</script>
The best I've found so far is
WebStorm, but its code completition is
easily distracted by imported
libraries (offering hundreds of
suggestions) and identical function
names.
This comment confuses me. If you import the libraries, and your code is using them, why is it bad to include the function names in the code completion suggestions? Wouldn't you want to have jQuery's functions included if you're using it?
If you're using Microsoft's IntelliSense with jQuery, does it stick to its guns and only show JavaScript core functions? Sounds limited to me, unable to be smart when I add libraries.
Or is something like this on it's [sic] way?
It sounds to me like you want a clairvoyant interface. I don't think it is on the way anytime soon.
By the way, "it's" == "it is"; "its" is the possessive.

Categories

Resources