Several days ago I tried to learn a little about Javascript language and AJAX. Implementing AJAX with pure Javascript is not an easy work. It is not cross-browser so that I have to detect which browser sent the AJAX request. I think some frameworks can solve the problem in a better way and finally I found a Javascript framework — Prototype.
I made a month-day selector using two drop lists. After you select a month, the number of the day drop list may change. For example, at first January is selected and the numbers of the day drop list are from 1 to 31. After you select April, the numbers of the day drop list becomes from 1 to 30. It is very easy to understand. I created two files, demo.html for showing page and response.php for calculate how many days a month has.
demo.html:
<html> <head> <script type="text/javascript" src="script/prototype-1.6.0.3.js"></script> <script type="text/javascript"> function send(value){ var length=$("day").length; for (i=0;i<length;i++){ $("day").remove(0); } new Ajax.Request( './response.php',{ method: "get", parameters: {month: value}, onSuccess: function(response){ var days=response.responseText; for (i=1;i<=days;i++){ $("day").options.add(new Option(i,i)); } }, onFailure: function(){ alert('Failed!'); } } ); } function init(){ for (i=1;i<=12;i++){ $("month").options.add(new Option(i,i)); } for (i=1;i<=31;i++){ $("day").options.add(new Option(i,i)); } } </script> </head> <body onload="init();"> <p> Month: <select id="month" onChange="send(this.value);"></select> Day: <select id="day"></select> </p> </body> </html>
response.php:
<?php $d=$_GET['month']; $days=array(31,29,31,30,31,30,31,31,30,31,30,31); echo $days[$d-1]; ?>
Sending an AJAX request with Prototype is using Ajax.Request. The code below is important:
new Ajax.Request( './response.php',{ method: "get", parameters: {month: value}, onSuccess: function(response){ var days=response.responseText; for (i=1;i<=days;i++){ $("day").options.add(new Option(i,i)); } }, onFailure: function(){ alert('Failed!'); } } );
The Ajax.Request contructor needs two arguments. The first is the target file and the second is an Ajax.Options object. The second parameter in this example is expressed as a JSON string. “method” indicates using “get” or “post” method. “onSuccess” and “onFailure” indicate the callback functions. With Prototype framework’s help, sending AJAX requests is very easy and intuitive.
Tags: Javascript, Programming, Web
Hello webmaster
I would like to share with you a link to your site
write me here preonrelt@mail.ru
Hey, I came across this blog article while searching for help with JavaScript. I have recently changed browsers from Opera to Microsoft Internet Explorer 5. After the change I seem to have a issue with loading JavaScript. Every time I go on a website that needs Javascript, the page freezes and I get a “runtime error javascript.JSException: Unknown name”. I cannot seem to find out how to fix it. Any aid is very appreciated! Thanks