Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

How do I mix up Perl and jQuery (for beginners)

by eyekona (Acolyte)
on Aug 21, 2013 at 13:45 UTC ( [id://1050351]=perlquestion: print w/replies, xml ) Need Help??

eyekona has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I'm a perl-beginner. I'm working at a project where I read data from a db and generate a html page with the results using print "<htmlcode>". Testing with apache2.

Now my boss wants to have some functions like drop-down boxes and stuff to make using my page more compfortable - and he wants me to use jquery for that.

Ok after reading and trying out some tutorials I can use a little jquery on a html page and I can use some perl to get the data. But how do I use both on the same page? I googled for an example but all of them were too complicated for me.

Do I also have to "print" the jQuery functions with perl and where do i put that jquery.js file so the generated html page finds it? Or is there any other way to mix them up? And is there a BETTER way to make a html page with perl without having to print every line? I've read something about html::template but couldn't figure out how it works on my own.

I'm asking for a very simple example of a html page using perl to get some data and jquery to display it. Is there a SIMPLE example you can give me or a link with a BEGINNERS guide?

Please help me. Normally I'm programming java and now all of a sudden i got this really big project with html/css(never used before) and perl(used once in university) and jquery (never even heard of before). Perl seems interesting but is so different from everything I did before...

  • Comment on How do I mix up Perl and jQuery (for beginners)

Replies are listed 'Best First'.
Re: How do I mix up Perl and jQuery (for beginners)
by daxim (Curate) on Aug 21, 2013 at 14:02 UTC
    I'm making some assumptions here. Your confusion stems probably from the fact that you have little idea how the Web works on the HTTP message level. Read a book or two about modern Web development, the concepts should transfer easily to your tools of choice. Following is a very small PSGI application to get you started. The application-specific JavaScript can also be put into a stand-alone file. Yes, a templating system is a good idea. So is using a Web framework, which is a small step up from printing out HTML piecewise.
    my $app = sub { return [200, ['Content-Type' => 'application/xhtml+xml'], [<<'END_ +HTML']]; <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></scr +ipt> <script> jQuery(document).ready(function(){ jQuery('p').append(' Hello world from jQuery!'); }); </script> </head> <body> <p>Greetings.</p> </body> </html> END_HTML };

    edit: JS does not need to be in the HTML

      You are right i have no idea how old or modern web applications work and i just know the theory about http and html i learned in university some years ago...

      I would love to read a book or two and learn perl, html and jquery properly but my boss wants to see some results on monday also i told him i have no idea of web programming and never done something like this before...

      I'm not asking you to do my work just asking for the simplest of an example you can give me to have something to beginn with.

      I already wrote some thousand lines of code and to my own surprise it works - it just doesn't look the way he wants it to - and now he forces me to use this jquery stuff so for example he don't want to type a name, he searches the data for, but else select one from a drop-down box which gets the names from the db - and i have no idea how to do that...

      I really appreciate your help. Thank you.

        It sounds like you need to spend time reading up on jQuery and AJAX. Your description reads like your boss wants you to use jQuery and AJAX to query a database, via server side Perl. Perhaps he saw your "some thousand lines of code" and doesn't think it's going to be maintainable. jQuery does a lot of heavy lifting for you, it's a widely used framework. If you were concerned by this requirement I suspect you'd have asked your boss about this already. Using Perl, jQuery, and JSON for Web development should be of interest.

        Update: added a few words to second sentance.

Re: How do I mix up Perl and jQuery (for beginners)
by davido (Cardinal) on Aug 21, 2013 at 17:10 UTC

    Your boss's expectations of "results by Monday" are unrealistic given your existing level of knowledge in the problem domain of web development. I'm not saying this to discourage you, nor to get you canned. I think that if I were your boss I would appreciate knowing early on what is and isn't realistic. Some bosses would be less forgiving, but others will be glad to work with you. It all depends on your relationship with him or her, and whether he or she is willing to work with you.

    Sit down with your boss and show him Twitter Bootstrap. It can be used easily with modern web frameworks like Dancer, Mojolicious and Catalyst. Dancer and Mojolicious have the lowest learning-barrier to entry of the three largest Perl-based modern server-side frameworks. And Bootstrap offers much of what you can do with jQuery, without as much of a learning curve. Bootstrap is a CSS framework that offers pop-ups, modals, and other "javascriptish" features, without forcing you to get into the low level details.

    If I had to get results by Monday, including pop-up dialogues, I myself would start by downloading Twitter Bootstrap.


    Dave

      I know, that it is unrealistic - and i said it to him from the start - so he should know... but he gave me the task anyway and i'm clearly not in the position to say "get someone else for this task who is better at it then i am".

      I don't even know what "getting canned" mean . i tried to look it up in a dictionary but it doesn't make any sense... ^^

      My boss also said exactly what programming-languages i have to use, so - although it looks nice - no twitter bootstrap for me...

      What is Mojolicious btw? I've heard that a couple of times... I think i'm going to look it up.

        "getting canned" == "terminated from employment". In other words, I do hope that your employer is reasonable, and not looking for a reason to let you go.

        Twitter Bootstrap is a CSS framework that uses jQuery. By using Bootstrap's Javascript features, you're pulling in jQuery, and using it. If you want to go beyond what Twitter Bootstrap provides, you have jQuery at your fingertips. But TB provides a lot already, and will save you a ton of time. Even if you only use it for dialogues and modals, it will save you time.

        Mojolicious is a server-side web framework. It facilitates Model/View/Controller style web design. It offers templating, routing, and a lot more.

        Dancer is another good alternative with low barriers to entry (although Mojolicious installs from a single tarball in under a minute). Both are pretty easy to learn.

        Catalyst is more of a chore to learn, but extremely powerful and configurable. With the power and configurability comes headaches. But it's a solid choice for large projects.


        Dave

Re: How do I mix up Perl and jQuery (for beginners)
by Your Mother (Archbishop) on Aug 21, 2013 at 15:49 UTC

    While this might be just as confusing as things you've seen or tried, it's minimal and available: CGI/Ajax example: lookup a value when a field is filled in.

    The main problem with web development isn't that any part of it is hard, it's not, it's that there are so many moving parts. Writing dynamic forms / ajax stuff + the backend is not a beginner task, even for someone seasoned in other programming. You might be feeling lost and like Perl is a wasteland but I assure you it's one of the best for web work; as is jQuery. If you post code you are working on, you'll probably get good help.

    One thing you said leads me to believe you are using CGI and doing this kind of thing-

    print "Content-Type: text/html\r\n\r\n", print "<html>...this"; print "that...</html>";

    There are many ways to get output out in Perl. The CGI.pm proper module is quite old-school. It's not a first choice for production but sometimes can be for one-offs and learning as long as you're aware better (more robust, testable, and reusable) approaches exist. Still, it's serviceable and stronger than most give it credit. You can, e.g., one page, one print-

    use strict; use warnings; use CGI ":standard"; print header(), start_html("OHAI"), h1("Bingo"), blockquote( p([ "one", "two", "three" ]), ), end_html();

      Yes this is exactly what i was doing till now - print html - so this is called CGI?

      I was wondering how i can get something from perl to an existing html page but could not find a way, but it seems this way is called json... some of the others mentioned it and it is also in your example. So thank you very much for posting this. I will try it out and see if i unterstand how it works. :-)

      Update: Works perfectly and seems to be the best approach. Just have one question to get it to work with my own existing database

      How is this structure

      return [ { username => "paco", fish => "Sunfish", }, { username => "YourUncle", fish => "Coelacanth", }, { username => "hiragana", fish => "Monkfish", }, { username => "MosaicNL", fish => "Sixgill Shark", }, ];

      called? Thats not a normal array - what's the name of it?

        How is this structure called?

        That's an (anonymous, no named variable) array reference which holds hash references. See perlref, and really! Do read it.

        use JSON; use Data::Dump "dump"; dump( other_way() ); # This will show the anonymous structure. print "JSON: ", to_json( other_way() ), $/; sub other_way { my %user1 = ( username => "paco", fish => "Sunfish" ); my %user2 = ( username => "YourUncle", fish => "Coelacanth" ); my %user3 = ( username => "hiragana", fish => "Monkfish" ); my %user4 = ( username => "MosaicNL", fish => "Sixgill Shark" ); my @users = ( \%user1, \%user2, \%user3, \%user4 ); return \@users; }

        NB: the dump() can appear "out of order" because it goes to STDERR. Output-

        [ { fish => "Sunfish", username => "paco" }, { fish => "Coelacanth", username => "YourUncle" }, { fish => "Monkfish", username => "hiragana" }, { fish => "Sixgill Shark", username => "MosaicNL" }, ] JSON: [{"fish":"Sunfish","username":"paco"},{"fish":"Coelacanth","user +name":"YourUncle"},{"fish":"Monkfish","username":"hiragana"},{"fish": +"Sixgill Shark","username":"MosaicNL"}]

        You can see in &other_way above how much more terse and more clean anonymous structures tend to be.

        Here's a very simple demo of an auto-complete input field using html/mysql/json

        HTML file
        <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>autocomplete demo</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/s +moothness/jquery-ui.css"> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> </head> <body> <label for="autocomplete">Select : </label> <input id="autocomplete"> <script> $( "#autocomplete" ).autocomplete({ source: "http://localhost/test/data.cgi", }); </script> </body> </html>
        data.cgi to provide data
        #!/usr/bin/perl use CGI; use DBI; use JSON; my $dbh = get_dbh(); # your connect details # test data $dbh->do('CREATE TEMPORARY TABLE json ( col1 char(3))'); for ("ABC", "BCD", "CDE", "DEF", "EFG", "FGH", "GHI"){ $dbh->do('INSERT INTO json VALUES (?)',undef,$_); } # query database my $q = CGI->new(); my $sth = $dbh->prepare('SELECT * FROM json WHERE col1 like ?'); $sth->execute('%'.$q->param('term').'%'); my @data=(); while ( my @f = $sth->fetchrow_array){ push @data,$f[0]; } print "Content-type: application/json; charset=iso-8859-1\n\n"; print JSON::to_json(\@data);
        poj
Re: How do I mix up Perl and jQuery (for beginners)
by golux (Chaplain) on Aug 21, 2013 at 16:34 UTC
    Hi eyekona,

    Here's another simple example of jQuery and Perl (as well as AJAX) that I just created as a reference.

    jQuery is nothing more than a Javascript library (albeit a very powerful one!), so you will need to learn Javascript in conjunction with it for doing client-side programming.

    AJAX is a technique for communicating asynchronously from the Client to the Server, which can be done in plain Javascript but is made extremely more easy by jQuery.

    I have intentionally omitted JSON (a mechanism for handling data based on Javascript syntax), but at some point you may want to learn that as well, especially when passing more complicated data between the Client and Server.

    You have a lot of learning ahead of you -- I wish you good luck and great fun!

    say  substr+lc crypt(qw $i3 SI$),4,5
      Thank you so much for posting this. I will try it out and see if i unterstand how it works. So now there are three examples for me to keep working on. So glad i found this site. :-)
Re: How do I mix up Perl and jQuery (for everyone)
by Anonymous Monk on Aug 21, 2013 at 13:58 UTC
      Help? Now I'm even more confused...

        Help? Now I'm even more confused...

        <Nelson Muntz>Ha-ha!</Nelson Muntz>

        Pick one (or twelve), reach a target website, see if the example/tutorial is simple enough for your needs (count pages or something), study it

        watch the video

        There are at least 5 one page example/articles

        perl speaks http, jquery speaks http, jquery speaks dom (html)

        where is the confusion?

Re: How do I mix up Perl and jQuery (for beginners)
by sundialsvc4 (Abbot) on Aug 21, 2013 at 15:17 UTC

    Yes, see if your boss will spring for some training.   Maybe at a local community college?

    Let me see if I can set the stage for you a bit.   In a modern web application, there are two programs in play:

    1. The client, written in JavaScript and probably using some client-side toolkit such as JQuery, which runs on the end user’s computer, and ...
    2. The server, written (partly) in Perl, which delivers all of the web-page content to the client side and which then responds to incoming requests (AJAX ... JSON ...) that are subsequently generated by the client-side program.

    Most commonly, the user simply navigates to a page, and when he does so, that page includes <script> tags which cause the user’s browser to request and to download all the script content (including JQuery itself).   Then, say, a onload event, again on the user’s browser, causes the browser to start running all that code.

    That JavaScript code, running on the client’s browser, actually builds and runs most of the user-interface.   The server now takes a supporting role, not a starring one.   To obtain information, or to request that things be done, it issues asynchronous HTTP requests (AJAX ...) to the server, which is running programming that could have been written in Perl or Python or Java or Visual Basic (dot-Net) or anything-else.   Things such as “JSON” refer to encoding schemes by which the messages that are passed back-and-forth are formatted in a compact yet HTTP-compatible way.

    These are “elementary basics” of the scenario, but you must understand them thoroughly before anything else will make the slightest lick o’ sense.   Training exists.   Avail yourself of it.   In due time, “the little light will come on,” and don’t feel out-of-sorts just because it hasn’t done so quite yet.   There most assuredly was a time when all of us said, “huh?”

      "Yes, see if your boss will spring for some training. Maybe at a local community college?"

      OP goes on to say:

      "I would love to read a book or two and learn perl, html and jquery properly but my boss wants to see some results on monday also i told him i have no idea of web programming and never done something like this before."

      Yeah, i figured most of it out by myself but it's really nice to have it written in one explanation like this. Thank you :-)
Re: How do I mix up Perl and jQuery (for beginners)
by jakeease (Friar) on Aug 22, 2013 at 08:28 UTC
      Yeah, i found this website before - and i already use mysql and from what i've read by now i will need json. But i didn't think this example was "very simple" because i couldn't get it to work ^^

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1050351]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2024-04-23 10:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found