Difference between revisions of "JavaScript"
Line 11: | Line 11: | ||
== XMLHttpRequest Object == | == XMLHttpRequest Object == | ||
− | ''XMLHttpRequest'' | + | The ''XMLHttpRequest'' object handles communication with the web servers. To use it, you must first initialize a variable to be an instance of the ''XMLHttpRequest'' class. |
− | |||
var xmlHttp; | var xmlHttp; | ||
xmlHttp=new XMLHttpRequest(); | xmlHttp=new XMLHttpRequest(); | ||
− | Once you have an XMLHttpRequest, you can use it to send | + | Once you have an ''XMLHttpRequest'', you can use it to send requests to a server. Initially, you need to connect to the server side page you are interested in: |
− | xmlHttp.open("METHOD","REMOTE_URL",ASYNCRONOUS_FLAG); | + | xmlHttp.open("METHOD","REMOTE_URL", ASYNCRONOUS_FLAG); |
− | where METHOD is "GET" or "POST", | + | where METHOD is "GET" or "POST", REMOTE_URL is the page that you are going to send requests to, and ASYNCRONOUS_FLAG is true or false to indicate whether the calls should be made asynchronously or synchronously. In asynchronous communication, the client can do other things while waiting for the server response, whereas in synchronous communication, the client blocks execution and waits until the response comes back before proceeding. Once the object has been opened, you can then use the ''send'' method to send a request to the server. Note that you do not explicitly set data fields to send, because it is contained in the URL request. |
xmlHttp.send(null); | xmlHttp.send(null); | ||
+ | The ''XMLHttpRequest'' object has an attribute, ''readyState'', that stores the current state of the request. | ||
− | |||
<table class="ex" border="1" width="50%" cellpadding="2" cellspacing="0" id="table7"> | <table class="ex" border="1" width="50%" cellpadding="2" cellspacing="0" id="table7"> | ||
<tr><th align="left" width="10%">State</th><th align="left">Description</th></tr> | <tr><th align="left" width="10%">State</th><th align="left">Description</th></tr> | ||
<tr><td>0</td><td>The request is not initialized</td></tr> | <tr><td>0</td><td>The request is not initialized</td></tr> | ||
<tr><td>1</td><td>The request has been set up</td></tr> | <tr><td>1</td><td>The request has been set up</td></tr> | ||
− | |||
<tr><td>2</td><td>The request has been sent</td></tr> | <tr><td>2</td><td>The request has been sent</td></tr> | ||
<tr><td>3</td><td>The request is in process</td></tr> | <tr><td>3</td><td>The request is in process</td></tr> | ||
Line 37: | Line 35: | ||
</table> | </table> | ||
− | For example, when a request is sent, the state is set to '' | + | For example, when a request is sent, the state is set to ''2''. Every time the state changes, javascript automatically calls a function specified by the ''onreadystatechange'' attribute. So, before calling a remote site, you should setup a new function: |
xmlHttp.onreadystatechange=function() { | xmlHttp.onreadystatechange=function() { | ||
Line 43: | Line 41: | ||
} | } | ||
− | This is | + | This is how asynchronous requests are handled. Once you send a request, you access the response only through the ''onreadystatechange'' function. Meanwhile, your client page can be doing other things. If you are waiting for a response from the server, you should check whether the ''readyState'' is ''4'', corresponding to the request being completed. The server's response is returned as part of the ''XMLHttpRequest' ''responseText'' attribute. |
xmlHttp.onreadystatechange=function() { | xmlHttp.onreadystatechange=function() { | ||
Line 51: | Line 49: | ||
} | } | ||
− | For example, | + | For example, if you have following html file, server.html: |
− | server.html | ||
<code> | <code> | ||
Line 64: | Line 61: | ||
</code> | </code> | ||
− | This server page just prints hello world message. | + | This server page just prints the hello world message. |
Here is an AJAX implementation that gets the message from the server and prints it. | Here is an AJAX implementation that gets the message from the server and prints it. | ||
Line 92: | Line 89: | ||
</pre> | </pre> | ||
</code> | </code> | ||
+ | |||
==Sending Parameters== | ==Sending Parameters== | ||
The parameters are send either in the url (to, for example, a PHP page) or through ''send'' function. | The parameters are send either in the url (to, for example, a PHP page) or through ''send'' function. |
Revision as of 21:29, 19 September 2009
Contents
Javascript
You should start by reading the w3schools javascript tutorial, which covers most of the important features of the language:
http://www.w3schools.com/js/default.asp
Asynchronous JavaScript And XML
AJAX, Asynchronous Javascript And XML, is a group of related web development techniques, standards, and technologies used on the client (web browser) side of the standard web server-client communication model. Although other languages can be used, the most common is to use javascript to send asynchronous requests to the web server in order to retrieve XML data that the javascript then uses to produce dynamic, fast, user-friendly web pages. The key idea is that most of the work happens at the web browser, keeping waiting times for data to come back over the network to a minimum.
The javascript XMLHttpRequest object is used to exchange data with the web servers without needing to reload the entire web page in the browser. This XMLHttpRequest object is now supported by all major browsers, although some browsers implement support in slightly different ways, leading to different behavior of the same code on different platforms. For this course, you should focus on supporting Firefox, but in any real production website it's very important to do validation testing using all of the major browsers including Firefox, Internet Explorer, Safari, and Opera as a minimum.
XMLHttpRequest Object
The XMLHttpRequest object handles communication with the web servers. To use it, you must first initialize a variable to be an instance of the XMLHttpRequest class.
var xmlHttp; xmlHttp=new XMLHttpRequest();
Once you have an XMLHttpRequest, you can use it to send requests to a server. Initially, you need to connect to the server side page you are interested in:
xmlHttp.open("METHOD","REMOTE_URL", ASYNCRONOUS_FLAG);
where METHOD is "GET" or "POST", REMOTE_URL is the page that you are going to send requests to, and ASYNCRONOUS_FLAG is true or false to indicate whether the calls should be made asynchronously or synchronously. In asynchronous communication, the client can do other things while waiting for the server response, whereas in synchronous communication, the client blocks execution and waits until the response comes back before proceeding. Once the object has been opened, you can then use the send method to send a request to the server. Note that you do not explicitly set data fields to send, because it is contained in the URL request.
xmlHttp.send(null);
The XMLHttpRequest object has an attribute, readyState, that stores the current state of the request.
State | Description |
---|---|
0 | The request is not initialized |
1 | The request has been set up |
2 | The request has been sent |
3 | The request is in process |
4 | The request is complete |
For example, when a request is sent, the state is set to 2. Every time the state changes, javascript automatically calls a function specified by the onreadystatechange attribute. So, before calling a remote site, you should setup a new function:
xmlHttp.onreadystatechange=function() { alert('state changed to '+xmlHttp.readyState); }
This is how asynchronous requests are handled. Once you send a request, you access the response only through the onreadystatechange function. Meanwhile, your client page can be doing other things. If you are waiting for a response from the server, you should check whether the readyState is 4, corresponding to the request being completed. The server's response is returned as part of the XMLHttpRequest' responseText attribute.
xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4){ .... do some cool stuff ... } }
For example, if you have following html file, server.html:
<html>
<body>
hello world
</body>
</html>
This server page just prints the hello world message.
Here is an AJAX implementation that gets the message from the server and prints it.
<html>
<body>
<script>
var xmlHttp;
xmlHttp=new XMLHttpRequest();
xmlHttp.open("GET","server.html",true);
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4){
var pElement=document.getElementById("msg");
pElement.innerHTML=xmlHttp.responseText;
}
}
xmlHttp.send(null);
</script>
<p id="msg"></p>
</body>
</html>
Sending Parameters
The parameters are send either in the url (to, for example, a PHP page) or through send function. Consider following PHP code that takes two parameters, multiplies them and return the result.
multiply.php
<html>
<body>
<? echo $_GET["x"]*$_GET["y"]?>
</body>
</html>
We can then use AJAX to get the multiplication of two numbers:
multiply-ajax.php
<html>
<body>
<script>
function multiply (){
var xmlHttp;
xmlHttp=new XMLHttpRequest();
var x,y;
x=document.getElementById("input_x").value;
y=document.getElementById("input_y").value;
xmlHttp.open("GET","multiply.php?x="+x+"&y="+y,true);
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4){
var pElement=document.getElementById("msg");
pElement.innerHTML=xmlHttp.responseText;
}
}
xmlHttp.send(null);
}
</script>
x:<input id="input_x" type="text"/ ><br>
y:<input id="input_y" type="text"/>
<a href="javascript:multiply();">Multiply</a>
<br>
------------------------</br>
Result:
<p id="msg"></p>
</body>
</html>
Note that x and y values are sent in url. You can also send them in send function, provided that your receiving page asumes they are form posts.
multiply-post.php
<html>
<body>
<? echo $_POST["x"]*$_POST["y"]?>
</body>
</html>
multiply-ajax.php
<html>
<body>
<script>
function multiply (){
var xmlHttp;
xmlHttp=new XMLHttpRequest();
var x,y;
x=document.getElementById("input_x").value;
y=document.getElementById("input_y").value;
var req="x="+x+"&y="+y;
xmlHttp.open("POST","multiply.php",true);
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4){
var pElement=document.getElementById("msg");
pElement.innerHTML=xmlHttp.responseText;
}
}
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", req.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(req);
}
</script>
x:<input id="input_x" type="text"/ ><br>
y:<input id="input_y" type="text"/>
<a href="javascript:multiply();">Multiply</a>
<br>
------------------------</br>
Result:
<p id="msg"></p>
</body>
</html>
Moving a target with Jquery
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
// these are for storing target locations
var targetLeft=0;
var targetTop=0;
function moveTarget(){
targetLeft+=10; //increase target location
targetTop+=10;
$("#target").css("top",targetTop); //move target to (top,left)
$("#target").css("left",targetLeft);
if(targetLeft<200) { //stop if we reached left=200
window.setTimeout("moveTarget()",200); //set the next timer
}
}
$(document).ready(function() { //at the beginning create a clock timeout
window.setTimeout("moveTarget()",200); //call this function in 200 ms.
});
</script>
</head>
<body>
<!-- this is my target-->
<img id="target" src="http://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/180px-Smiley.svg.png" style="position:relative"/>
</body>
</html>