How to Create a Simple Perl AJAX Application? An Easy Tutorial on Working With AJAX and Perl

in utopian-io •  7 years ago  (edited)

AJAX is a simple technique that allows any programmer to create applications that can be used as part of web pages. Perl is no exception and AJAX works well with it.

It is always worth repeating the fact that AJAX (Asynchronous Javascript and XML) is not a new programming language, it is a technique. It is a technique that allows a web page designer to use a Javascript to communicate with a program held on the web server, and then use the response from the server within their web page. This, of course, is a major advantage for any Perl programmers. It means that the Perl programmer can:

  • build a Perl application on a web server
  • incorporate the Perl application into a web page (or even many web pages)



And the general technique is always the same:

  • the Javascript web page sends a request to the web server
  • the web server processes the request and then replies to the web page
  • the web page processes or displays the response from the web server

The starting point for the programmer is, therefore, to create a Perl CGI application.

Creating a Simple Perl CGI Web Page

The first line of a CGI application must always be the shebang line. This tells the web server where to locate the Perl interpreter:

#!c:/Perl/bin/perl


The second line of a CGI application should then output the page's HTML header to the web browser:

print "Content-type: text/html\n\n";

Once those two compulsory lines are in place the programmer can start building the main functionality of the application. In this example the application will calculate the times for sunrise and sunset for the current day. Therefore the correct module must be used. In this case it's the Astro Sunrise module:

use Astro::Sunrise;


This requires an input of the latitude and longitude of a location on the surface of the Earth:

$latitude = 52.62;
$longitude = -0.48;


From this the times for sunrise and sunset can be produced:

$sun_rise = sun_rise ($longitude, $latitude);
$sun_set = sun_set ($longitude, $latitude);


And then returned:

print $sun_rise . " - " . $sun_set;


If this is saved into a file in the server's CGI directory then it can be tested (as seen in figure 1 at the bottom of this article). And then it is ready to be turned into an AJAX application.

Turning a Perl Script into an AJAX Application

Every AJAX application starts in the same way - it creates an XML HTML request object:

<head>
<script type = "text/javascript">
var XMLHttp;
if(navigator.appName == "Microsoft Internet Explorer") {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
XMLHttp = new XMLHttpRequest();
}


And every AJAX application requires a function that will:

  • send a request to the server
  • wait until the server has completed its processing of the request
  • display the results

The function will call the simple Perl CGI application already saved on the server:

function show_sun_rise () {
XMLHttp.open("GET", "/cgi-bin/simple_ajax.pl", true);
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState == 4) {
document.getElementById( 'time_div' ).innerHTML = XMLHttp.responseText;
}
}
XMLHttp.send(null);
}
</script>
</head>


Then a little HTML is required. In this example it defines a button (which will call the request function) and it also defines an area that will be used to display the result:

<body>
<input type = button onclick = "javascript: show_sun_rise ()" value = "Show Sunrise and Sunset Times">
<div id = "time_div">
Click the button to see the times for sunrise and sunset
</div>
</body>

Adding Input Variables to the Perl CGI Web Page

At the moment longitude and latitude have been hard coded into the script. However, it is much more useful allow the users to set these. Fortunately user inputs are easy to handle in Perl and so it is just a matter of loading another module:

use CGI qw/:standard/;


And then handling the inputs (if there are any):

if (param('latitude')) {$latitude = param('latitude')}
else {$latitude = 52.62}
if (param('longitude')) {$longitude = param('longitude')}
else {$longitude = -0.48}


Again this should be test before moving on.

The Completed AJAX Application

The AJAX application will now need a small amount of modification. It will require input boxes for the user to enter their latitude and longitude:

Latitude<input id=latitude><br />
Longitude<input id=longitude><br />


And the function for sending the request will have to be altered so that it adds the longitude and latitude as part of the query string:

function show_sun_rise () {
var query_string = "?latitude=" + document.getElementById('latitude').value;
query_string = query_string + "&longitude=" + document.getElementById('longitude').value;
XMLHttp.open("GET", "/cgi-bin/simple_ajax.pl" + query_string, true);
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState == 4) {
document.getElementById( 'time_div' ).innerHTML = XMLHttp.responseText;
}
}
XMLHttp.send(null);
}


This complete AJAX application will be able to:

  • accept inputs from a user
  • format the inputs and send them to a web server
  • process the input on the server
  • return a result from the server to the web page
  • display the results on the web page

And all this done through the power of Perl programming (with a little help from Javascript :) ).

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Eser daghanla neden ugrasiyosun acaba ogrene bilirmiyim

  ·  7 years ago (edited)

İnsanlara küfür ediyor. Uygunsuz paylaşımlar yapıyor. İnsanlara rahatsızlık veriyor.

Bunlardan vazgeçmesi gerekir. Tüm herkesten özür dilesin. Ve uygunsuz paylaşımlar yapmaktan vazgeçsin.

Aksi halde tüm postları flag alacak.

Duydunmu beni Atlıhan?

Tüm hesapları flag alacak. okuzoldi steemiterturk medusa kolleksiyonu ve diğer tüm hesapları flag alacak. Ya hatasını kabullenip kendini düzeltir ya bu şekilde devam eder.

sen boyle yaptıkca ınsanlara bulasoyor farkındamısın senın yuzunden kac kısının canı yanıyor flag atma ugrasma kardesım zaten gozukmuyor okey.

atli ve daghan hesaplarının icabına baktığım için gözükmüyor. Sıra diğer hesaplarında. Ya postlarını yorumlarını düzeltir yada açtığı tüm hesaplar görünmez olacak.

This post has received a 3.93% upvote from @lovejuice thanks to @eser. They love you, so does Aggroed. Please be sure to vote for Witnesses at https://steemit.com/~witnesses.

This post has received a 0.5 % upvote from @boomerang thanks to: @eser

@boomerang distributes 100% of the SBD and up to 80% of the Curation Rewards to STEEM POWER Delegators. If you want to bid for votes or want to delegate SP please read the @boomerang whitepaper.

You got a 0.65% upvote from @postpromoter courtesy of @eser!

sıra geldi diğer hesaplarına

senin asıl hesabın ne olacak @eser

hahahahaha

Git kumda oyna Atlıhan

This post has received a 3.93% upvote from @lovejuice thanks to @eser. They love you, so does Aggroed. Please be sure to vote for Witnesses at https://steemit.com/~witnesses.

This post has received a 0.54 % upvote from @boomerang thanks to: @eser

@boomerang distributes 100% of the SBD and up to 80% of the Curation Rewards to STEEM POWER Delegators. If you want to bid for votes or want to delegate SP please read the @boomerang whitepaper.

This post has received a 0.75 % upvote from @boomerang thanks to: @eser

@boomerang distributes 100% of the SBD and up to 80% of the Curation Rewards to STEEM POWER Delegators. If you want to bid for votes or want to delegate SP please read the @boomerang whitepaper.

This post has received a 7.12% upvote from @lovejuice thanks to @eser. They love you, so does Aggroed. Please be sure to vote for Witnesses at https://steemit.com/~witnesses.

You got a 0.69% upvote from @postpromoter courtesy of @eser!

benim listeme de bir çok isim girer seni şimdi buldum. öküzöldü ben değilim oradan kaybettin medusa listesi seni zaten yanılttı o moorkedi de steemiterturk tıpkı öküzüldu gibi kimdir bilemem ama ben seni artık artık tanıyorum ....sana attığım bütün yemleri yuttun...

Benim ile derdiniz nedir ve kimsiniz bilmiyorum. lütfen paylaşımlarıma dokunmayınız eser bey hiç bir postumda hata olduğunu düşünmüyorum yaptığınıza da bir anlam veremedim.

  ·  7 years ago Reveal Comment

arkadaş benim sorunun ne? seni tanımam etmem sen de beni nereden tanırsın bilmem. @dağhan arkadaşın dediğine göre onun postlarını beğendiğim için bana flag vermişsin . buraya ilk geldiğimde o bana yardım etti. sonuna kadar beğenirim bütün postlarını.

Congratulations @eser! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of comments received

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Hey @eser I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

  ·  7 years ago Reveal Comment
  ·  7 years ago Reveal Comment

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

  ·  7 years ago Reveal Comment