FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


Java tutorials





aceman14
Does anybody know of some good java tutorials, i know the basics in java and the biggest project i have made is Yahtzee. Specifically i want tutorials that will teach me basic 2D gaming.
Stubru Freak
http://www.dgp.toronto.edu/~mjmcguff/learn/java/
aceman14
Thanks a ton, this is definitely a site im gona use.
sinaryuda
It's sad but true - error-free code is still largely a Utopian dream. No matter how careful you are, no matter how deep your knowledge or how good your IDE, you're bound to slip up sooner or later. And when you do, and your routines decide to go AWOL, you need to take remedial action.

Most programming languages come with built-in exception handling capabilities. These exception handlers make it possible to catch errors and resolve them sensibly, thereby insulating the user from complex decisions and incomprehensible technical information. As a professional developer, you should always wrap your code in exception handling routines, if only to avoid embarrassing flameouts in front of your customers.

Up until recently, JavaScript was *not* one of the languages with sophisticated exception handling. Most of the time, developers were stuck with the built-in JavaScript debugger to track errors in their scripts, and had to unhappily consent to the browser taking care of errors for them in the most direct way possible - an ugly pop-up in the user's face. All that has changed, though, with the arrival of JavaScript 1.5 (available from Internet Explorer 6.0 and Netscape 6.0), which finally allows developers to wrap their code in "try-catch" exception handlers and discreetly resolve errors internally, at the application layer itself.

That's where this article comes in. Over the next few pages, I'm going to be looking at exception handling, with a special focus on exceptions in the JavaScript universe. I'll be explaining the most common error types you'll encounter, together with the JavaScript constructs you can use to catch and resolve them, and I'll include lots of examples so that you can see how it works in practice. So come on in, and let's get started.

Normally, when a JavaScript program encounters an error, be it syntactical or logical, it exits the program at that stage itself with a message indicating the cause of the error. Now, while this behaviour is acceptable during the development phase, it cannot continue once a program has been released to actual users. In these "live" situations, it is unprofessional to display cryptic error messages (which are usually incomprehensible to non-technical users); rather, it is more professional to intercept these errors and either resolve them (if resolution is possible), or notify the user with a clear error message (if not).

The term "exceptions" refers to those errors which can be tracked and controlled. For example, if a function attempts an unsupported operation on a built-in JavaScript object (say, trying to assign values to a non-existent array index), JavaScript will generate a "TypeError" exception, together with a message explaining the problem. Exceptions like these can be caught by the application, and appropriately diverted to an exception-handling routine.

In earlier versions of JavaScript, exception handling was almost non-existent - developers were stuck with the standard error construct provided by the browser, and had little or no control over what happened with the JavaScript interpreter encountered an error. With JavaScript 1.5, all of that changed - the language now supports standard "try-catch" exception-handling constructs, and provides a far greater degree of control over how errors are processed.

An example might make this clearer. Consider the following simple line of code,


<script language="JavaScript">


colours[2] = "red";

</script>

In the example above, JavaScript tries to change the value of the second element of the array variable "colours". Now, this variable does not exist in the variable namespace. What does JavaScript do? Rather than quietly packing up and moving to a new neighbourhood, JavaScript decides to generate an exception.
An error has occurred in the script on this page. Line: 8 Char: 1 Error: 'colours' is undefined Code: 0 URL: http://localhost/errors.html

You can see this from the first few lines of the output, which describe the exception, together with the variable that caused it.

From the above output, it's pretty clear what happened - an error occurred because the "colours" variable doesn't exist. And JavaScript also provides primitive debugging information on the error, such as the line on which the errant code resides. A little analysis of this debug data, and you'll quickly be able to identify the lines of code involved in the error.

So that's what an error looks like. And now that you've seen what makes it tick, how about writing something to handle it?

JavaScript allows you to trap errors using the standard "try-catch" exception-handling combination. Here's what it looks like:


try {
execute this block
} catch (error) {
execute this block if error
}

Take a look at this rewrite of the previous example, which incorporates a simple exception handler.


<script language="JavaScript">


try {
colours[2] = "red";
} catch (e) {
alert("Oops! Something bad just happened. Calling 911...");
}

</script>

And this time, when the script is executed, it will not generate an error - instead, it will output
Oops! Something bad just happened. Calling 911...

This is a very basic example of how JavaScript exceptions can be trapped, and appropriate action triggered. As you will see, the ability to handle errors in a transparent manner throws open some pretty powerful possibilities...but more on that later.

The first part of the code introduces you to the "try" block; this instructs JavaScript to try - literally - to execute the statements within the enclosing block.


try {
colours[2] = "red";
}

The "catch" block sets up the exception handler, in the event that one is generated. This does the hard work of trapping the exception and suggesting how to handle it


catch (e) {
alert("Oops! Something bad just happened. Calling 911...");
}

If an exception is generated, the "catch" segment of the code will be triggered, and JavaScript's default error handling mechanism will be overridden by the instructions in that code segment - in this case, displaying the text "Something bad happened".

Now, what you just saw was a very primitive exception handler, albeit one which isn't very useful on a production site. Ideally, you'd want the message generated by the exception handler to be a little more descriptive, and to contain some information on the source of the error.

JavaScript satisfies this requirement via two special, pre-defined properties of the Error object generated by an exception - the "name" and "message" properties. Take a look:



<script language="JavaScript">


try {
colours[2] = "red";
} catch (e) {
alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); }

</script>

Here's the output:
An exception occurred in the script. Error name: TypeError. Error message: 'colours' is undefined

Don't want to use the alert() box because it's disruptive and annoying? Write the output directly to the page itself with the writeln() method instead, as below:


An exception occurred in the script!

Error name: ReferenceError

Error message: colours is not defined


It's also possible to write an exception handler to ignore all errors generated in your script - the following example demonstrates:


<script language="JavaScript">


try {
// generate an error
eval("some gibberish")
} catch (e) {
// ignore it
}

</script>

In this case, it doesn't matter what type of exception JavaScript generates
- the generic handler will catch it, ignore it and continue to process the rest of the script.

It should be noted, however, that this approach, although extremely simple, is *not* recommended for general use. It is poor programming practice to trap all errors, regardless of type, and ignore them; it is far better - and more professional - to anticipate the likely errors ahead of time, and use the "try-catch" construct to isolate and resolve them.

You can also write specific exception handlers for different types of exceptions, by using an "if" test to check the exception type within the "catch" block. Consider the following handler, which only handles TypeError exceptions:


<script language="JavaScript">


try {
colours[2] = "red";
} catch (e) {
if (e instanceof TypeError)
{
alert("Bad or undefined variable!");
}
}

</script>

Here's the output:
Bad or undefined variable!

Of course, this handler will now only restrict its activities to TypeError exceptions. All other errors will be ignored.

The JavaScript 1.5 specification defines six primary error types, as follows:

EvalError - raised when the eval() functions is used in an incorrect manner;

RangeError - raised when a numeric variable exceeds its allowed range;

ReferenceError - raised when an invalid reference is used;

SyntaxError - raised when a syntax error occurs while parsing JavaScript code;

TypeError - raised when the type of a variable is not as expected;

URIError - raised when the encodeURI() or decodeURI() functions are used in an incorrect manner;

You can trap more than one exception, and handle each one in a different way, by using multiple "if" constructs within a single "catch" block.


try {
execute this block
} catch (error) {
if (error instanceOf errorType1)
{
do this
}
else if (error instanceOf errorType2)
{
do this
}

... and so on ...

else
{
do this if none of the error types above match
}
}

If an exception is encountered while running the code within the "try" block, the JavaScript interpreter stops execution of the block at that point and begins checking each "if" test within the "catch" block to see if there is a handler for the exception. If a handler is found, the code within the appropriate "if" block is executed; if not, control moves to the "else" block, if one exists.

Once the "try" block has been fully executed and assuming that the program has not been terminated, the lines following the "try" block are executed.

Take a look at the next example, which demonstrates how this works by revising the example on the previous page::


<script language="JavaScript">


// ask for user input
code = prompt("Enter some JavaScript code");

// run the code and catch errors if any generated
try {
eval(code);
} catch (e) {
if (e instanceof TypeError)
{
alert("Variable type problem, check your variable definitions!")
}
else if (e instanceof RangeError)
{
alert("Number out of range!")
}
else if (e instanceof SyntaxError)
{
alert("Syntax error in code!");
}
else
{
alert("An unspecified error occurred!");
}
}

</script>

You can test this exception handler by entering different lines of code into the box that appears when you load the page into your browser.

* To generate a TypeError, try accessing a non-existent array subscript, like this:


alert(someArr[18])

* To generate a RangeError, try creating an array with an extremely large size, like this:


var someArr = new Array(89723742304323248456)

* To generate a SyntaxError, try entering a line of code with a deliberate error in it, like this:


vara count = 99

As you will, in each case, the exception handler above will identify the error type and display an appropriate alert message. The "else" block works as a catch-all exception handler, processing all errors which have not been accounted for in the preceding "if" clauses.

JavaScript also allows you to add a "finally" block to the "try-catch" block discussed previously. The "finally" block contains statements that are executed regardless of whether an exception is generated or not in the "try-catch" block.


try {
execute this block
} catch (error) {
execute this block if error
} finally {
execute this block after the try block
}

If an exception is encountered when running the code within the "try" block, JavaScript will stop execution at that point, and look for a "catch" block to handle it. Once the error has been handled (or if no "catch" block exists), control passes to the "finally" block.

Take a look at the next example to see how this works:


<script language="JavaScript">


// ask for user input
code = prompt("Enter some JavaScript code");

// run the code and catch errors if any generated
// after the error handling display goodbye message
try {
eval(code);
} catch (e) {
alert("The following error occurred: " + e.name + " - " + e.message); } finally {
alert ("Thank you for playing. Come back soon!");
}

</script>

Here's the output:
The following error occurred: TypeError - 'a' is undefined Thank you for playing. Come back soon!

It's important to note that the code in the "finally" block will be executed even if errors are encountered in the corresponding "try" block.

Thus far, you've been working with JavaScript's built-in exceptions, which can handle most logical or syntactical errors. However, JavaScript also allows you to get creative with exceptions, by generating your own custom exceptions if the need arises.

This is accomplished via JavaScript's "throw" statement, which is used to raise errors which can be detected and resolved by the "try" family of exception handlers. The "throw" statement needs to be passed an error type. When the exception is raised, this exception name and description will be made available to the defined exception handler.

Let's go to a quick example. In the following piece of code, if the value entered into the form field is greater than 99, the code will manually generate a RangeError exception, which will be caught and displayed appropriately.


<html>

<head>

<script language="JavaScript">


function checkAge()
{
try {
// if incorrect value in form
// generate an error
if (document.forms[0].age.value > 99)
{
throw RangeError;
}
} catch (e) {
// catch all thrown errors and print error type
alert(e.name);
}
}

</script>
</head>

<body>

<form>
<input type="text" name="age" onBlur="checkAge()">
</form>

</body>
</html>

You can also create your own exceptions, via the JavaScript Error constructor. The following example demonstrates, by creating a custom error type called idiotUserError.


Error
Idiot user detected, terminating...


In this case, when you run the script, a new Error object will be created named idiotUserError, with the message specified in the Error object constructor. This error can now be thrown using the regular "throw" statement, as in the example above.

Let's try a more useful example:


<html>

<head>

<script language="JavaScript">


// create new Error objects
badNameError = new Error ("System user name does not match actual user name"); noNameError = new Error ("System user name cannot be blank");

// create generic exception handler
// to display error message
// you may want to filter down error types
// further inside this and handle each type
// differently
function mainExceptionHandler(e)
{
alert (e.message);
}

// general form validation functions
function validateForm()
{
checkName();
}

// check form values
// if errors, throw appropriate exception
function checkName()
{
try {
if (document.forms[0].username.value == "")
{
throw noNameError;
}

if (document.forms[0].username.value != "john")
{
throw badNameError;
}
} catch (e) {
// any and all errors will go to this handler
mainExceptionHandler(e);
}
}

</script>
</head>

<body>

<form onSubmit="validateForm()">
Enter your system username: <input type="text" name="username"> <br> <input type="submit" name="submit" value="Go"> </form>

</body>
</html>

In this case, if the value entered into the form is blank or not "john", a custom exception will be thrown by the code. This custom exception can be caught by a generic exception handler such as the one used above, and the exception can be routed and resolved appropriately

And that just about covers it. In this article, I took you on a guided tour of exception handling in JavaScript, demonstrating how the "try" and "catch" blocks can be used to trap and resolve errors in script execution. I showed you how to retrieve the exception type and message, write exception handlers for different error types, and even generate your own custom errors. Finally, I wrapped things up with a real-world example that demonstrated how to build a simple form validator and generate exceptions suitable for processing by a generic "try-catch" handler.

In case you'd like to learn more about these topics, you should consider visiting the following links:

The official ECMAScript reference, at http://www.ecma-international.org/publications/standards/ecma-262.htm

JavaScript 1.5 reference material in the Netscape DevEdge documentation, at http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/st
mt.html#1051663

Handling errors in Internet Explorer, at http://msdn.microsoft.com/library/en-us/dnscrpt/html/WebErrors2.asp

Until next time...be good!

Note: Examples are illustrative only, and are not meant for a production environment. Code samples in this article have been tested on Microsoft Internet Explorer 6.0. Melonfire provides no warranties or support for the source code described in this article
sinaryuda
JavaScript's Window object comes with four methods that you can use to create timed or looping events in your Web pages. In this article, I'll introduce you to them, and also show you a few examples of how they can be used in different situations.

Some of the most common and beneficial uses of JavaScript involve timer functions. These functions are used to run client-side code at predefined intervals, thereby making it possible to add a new dimension - time to your Web pages. By using JavaScript's timing functions, you can run a command after a specified delay has passed, loop events to run over and over again at predefined times, and synchronize multiple events on a timeline. JavaScript's Window object comes with four methods that you can use to create timed or looping events in your Web pages. In this article, I'll introduce you to them, and also show you a few examples of how they can be used in different situations.

Over the course of this article, I'll be exploring the various timing functions available in JavaScript, together with examples of how they can be used to create timed events in an HTML document. I'll introduce you to the setTimeout(), clearTimeout(), setInterval() and clearInterval() functions, and also show you how to use them to create a variety of different client-side applications, including a tickertape, a timed slideshow, and a countdown clock. So come on in! If you're new to JavaScript, you're going to find this article to be quite an eye-opener!

Let's start at the top, with the setTimeout() and clearTimeout() methods. These methods belong to the Window object, and are commonly used to run a particular piece of code after a pre-defined interval has passed. Consider the following example:


<script language="JavaScript">
var t = window.setTimeout('alert("5 seconds have passed since you loaded
this page")', 5000);
</script>


In this case, the setTimeout() method is used to run the function 5000 milliseconds (5 seconds). Thus, there are always two arguments to the setTimeout() method; the first is the code to run, and the second is the amount of time to wait before running it.

Here's another, more useful example.


<script language="JavaScript">
var t = setTimeout('window.close()', 30000);
</script>


In this one, the window (which we'll assume has been popped open from some other parent window) closes automatically 30 seconds after it opens.

Just as you can set a timeout, you can also clear it with the clearTimeout() method. This method is used to remove a timeout previously declared with setTimeout(). Since there may be multiple calls to setTimeout() in the same document, it is mandatory to provide clearTimeout() with a reference so that it knows which timeout to clear. The following variant of the example above demonstrates:


<script language="JavaScript">
var t = window.setTimeout('window.close()', 30000);
window.clearTimeout(t);
</script>

In this case, the window will never close, because the clearTimeout() method will cancel the timeout previously created with setTimeout().

If you want to really obfuscate, you can clear a timeout after a specified interval, by wrapping the call to clearTimeout() in a call to setTimeout():


<script language="JavaScript">
var t = window.setTimeout('window.close()', 30000);
var c = window.setTimeout('window.clearTimeout(t)', 10000);
</script>


In this case too, the window will never close, because the first timeout will be cancelled 10 seconds in by the call to clearTimeout() in the second.

Here's another example, this one containing two timers. The first one is set to close the window after 30 seconds. However, 10 seconds in, the second one will activate and ask the user to confirm the timeout. If the user does not confirm it, the timeout will be cancelled.


<script language="JavaScript">
// set timeout for window to close
var win = setTimeout('window.close()', 30000);
// set timeout for user input
var check = setTimeout('checkStatus()', 10000);
// ask if user wants window to close
// if no, clear timeout for window to close
function checkStatus()
{
if(!window.confirm("This window will shut in 20 seconds. Is that OK?"))
{
window.clearTimeout(win);
}
}
</script>

Note that after the confirm() dialog bog is displayed and while it is waiting for a user click, all timers are suspended.

Here's another example, this one using the setTimeout() method to create a countdown clock. Take a look:


<html>
<head>
<script language="JavaScript">
var i=10;
function countDown()
{
if(i > 0)
{
document.forms[0].elements[0].value=i;
i = i-1;
var c = window.setTimeout("countDown()", 1000);
}
else
{
alert("Happy New Year!");
}
}
</script>
</head>
<body onLoad="countDown()">
<form>
<input type="text" name="counter" size="3">
</form>
</body>
</html>

In this case, I'm using the setTimeout() method to call itself in a loop every second, and updating the value of the countdown clock on every iteration of the loop. When the countdown hits 0, an alert box is displayed.

Next up, the setInterval() and clearInterval() methods. The main difference between these methods and the ones on the previous page is this: the setTimeout() and clearTimeout() methods are used to run a particular piece of code once after a pre-defined interval has passed, while the setInterval() and clearInterval() methods are used to run a piece of code over and over again, with a pre-defined interval between successive runs.

Consider the following example:


<script language="JavaScript">
var y = window.setInterval('alert("Yoohoo!")', 2000);
</script>

In this case, the alert() box will keep appearing, once every 2 seconds. Thus, there are always two arguments to the setInterval() method the first is the code to run, and the second is the amount of time between successive runs.

Here's another, more interesting example - creating a scrolling tickertape in the window's status bar:


<script language="JavaScript">
// ticket-tape message
var message = " A blue pig jumped over the yellow moon ";
// add and remove characters from the message
function tickerTape()
{
window.status = message;
message = message.substring(1, message.length) + message.substring(0, 1);
}
// start the ball rolling
window.setInterval("tickerTape()", 150);
</script>

In this case, I've created the appearance of a moving tickertape by taking one character off the beginning of the message string and adding it to the end. Each time the tickerTape() function is called, the first character of the string is deleted and added to the end of the string, simulating a scrolling ticker-tape. The setInterval() function takes care of calling the tickerTape() function over and over again, once every 150 milliseconds. Finally, the "status" property is used to assign the result at each stage to the browser's status bar.

Just as you can set an interval, you can also clear it with the clearInterval() method. Here too, you must provide clearInterval() with a reference so that it knows which interval to clear. The following variant of the example above demonstrates:


<html>
<head>
<script language="JavaScript">
// ticket-tape message
var message = " A blue pig jumped over the yellow moon ";
// add and remove characters from the message
function tickerTape()
{
window.status = message;
message = message.substring(1, message.length) + message.substring(0, 1);
}
// start the ball rolling
var s = window.setInterval("tickerTape()", 150);
</script>
</head>
<body>
<form>
<input type="button" value="Stop Scrolling" onClick="window.clearInterval(s)">
</form>
</body>
</html>

In this case, when you click the button, the clearInterval() method will cancel the timer set earlier with setInterval() and the tickertape will stop moving.

Using a setInterval() function is identical to using a setTimeout() function in a loop. To illustrate this, consider the following example by rewriting the countdown clock example from a few pages back.


<html>
<head>
<script language="JavaScript">
var i=10;
function countDown()
{
if(i > 0)
{
document.forms[0].elements[0].value=i;
i = i-1;
}
else
{
alert("Happy New Year!");
}
}
window.setInterval("countDown()", 1000);
</script>
</head>
<body>
<form>
<input type="text" name="counter" size="3">
</form>
</body>
</html>

In this case, I've used the setInterval() method instead of the setTimeout() method to call the countDown() function over and over again. Note the difference between the version above and the one a few pages back - above, the call to setInterval() is outside the loop, whereas earlier, the call to setTimeout() was inside the loop.

Here's one more example, this one making a <div> appear when the mouse moves over a link and automatically hiding it again after 3 seconds:


<html>
<head>
<script language="JavaScript">
function on()
{
if(document.all)
{
// make <div> visible
document.all['volume'].style.visibility='visible';
// after 3 seconds, make it invisible
window.setInterval("document.all['volume'].style.visibility='hidden'",3000);
}

if(document.layers)
{
// make <div> visible
document.volume.visibility='show';
// after 3 seconds, make it invisible
window.setInterval("document.volume.visibility='hide'",3000);
}
if(!document.all && document.getElementById)
{
// make <div> visible
document.getElementById("volume").style.visibility="visible";
// after 3 seconds, make it invisible
window.setInterval("document.getElementById('volume').style.visibility='hidd
en'",3000);
}
}
</script>
</head>
<body>
<a href="#" onMouseOver="javascript:on();">Show Volume Control</a>
<div id="volume" style="color:white; font-face:Arial; background:black;
position:absolute; left:550; top:200; height:150; visibility:hidden;">
Volume<br> control<br> slider<br> here
</div>
</body>
</html>

Let's look at a couple more examples, which demonstrate just how useful - and varied - these functions can be. This first one uses the setInterval() method to create a timed slideshow:


<html>
<head>
<script language="JavaScript">
// slideshow image counter
var i = 0;
function slideShow()
{
// set up list of images
slidesArray = new Array()

slidesArray[0]="image1.jpg"
slidesArray[1]="image2.jpg"
slidesArray[2]="image3.jpg"
slidesArray[3]="image4.jpg"
slidesArray[4]="image5.jpg"

// load image
document.images[0].src=slidesArray[i]

// increment counter
i=i+1;

// when at the end, start again
if(i==5) { i=0; }
}
</script>
</head>
<body onLoad="javascript:setInterval('slideShow()',5000);">
<img src="image1.jpg" name="image">
</body>
</html>

Here, the images to be displayed are stored in a JavaScript array, and a "for" loop takes care of pulling out the correct image from the array and loading it into the page. The setInterval() method is used to refresh the image with a new one every 5 seconds.

You can also use the setInterval() method to move things around on a Web page, by incrementing an X- or Y-coordinate of a page element at a predefined interval. Consider the following example, which demonstrates by moving a <div> containing an image of a car across the screen.


<html>
<head>
<script language="JavaScript">
function moveCar()
{
if(document.all)
{
document.all("car").style.pixelLeft+=1;
if(document.all("car").style.pixelLeft >= (document.body.offsetWidth-30))
document.all("car").style.pixelLeft=-30;
}
if(document.layers)
{
parseInt(document.car.left+=5);
if(window.innerWidth-parseInt(document.car.left)<0)
document.car.left=-30;
}

}
</script>
</head>
<body onLoad="javascript:setInterval('moveCar()', 1)">
<!-- layer containing car image -->
<div id="car" style="position:absolute; left:20; top:200; width: 150;
height:50;">
<img src="rolls_royce.jpg" width=400 height=500 alt="" border="0">
</div>
</body>
</html>

Finally, I'll wrap things up with a more practical example, one which might come in handy in your Web development. In this next example, the task is to offer the user a file upload box, which he or she can use to upload files to a Web site. Once the user selects a file for upload and initiates the transfer, a dialog box should pop up with a message asking the user to be patient. Once the file upload completes, the dialog box (window) should automatically disappear.

Now, there are a number of ways to implement this. Here's how I'm going to do it:

1. Write the code to display a form for file upload, as well as the code to accept the file and transfer it to a data directory on the server. This will be implemented in PHP.

2. Add code to the script above to throw up a pop-up window once the upload begins.

3. Add code to the pop-up window to keep polling the parent window for file upload status. Once the upload has finished (signified by the parent browser window loading a new URL), the pop-up window will automatically close.

First, the code for the form:


<html>
<head>
</head>
<body background="images/bkgd.gif" leftmargin="0" rightmargin="0"
marginheight="0" marginwidth="0" topmargin="0">
<form action="upload.php" method="POST"
onSubmit="window.open('wait.html','resultsWindow','toolbar=no,location=no,
directories=no,status=no,menubar=no,scrollbars=no,
resizable=no,copyhistory=no,
width=500,height=400');" enctype="multipart/form-data" >
Attach File
<br>
<input name="file" type="file" size="30" maxlength="50">

<br>
<input type="submit" value="Submit">
</body>
</html>

Now, the server-side PHP script which processes the file submitted by the user through the form above:


<?php
// upload.php
// upload the file to the server
if($_FILES['file'][name] != "")
{
if (is_uploaded_file($_FILES['file']['tmp_name']))
{
// if the file is clean, move it to final location
if(file_exists($_FILES['file']['tmp_name']))
{
// check the size of the file
if($_FILES['file']['size'] < $file_limit)
{
// get the file name
$NAME = $_FILES['file']['name'];
// copy it to data directory
if(copy($_FILES['file']['tmp_name'], $UPLOAD_LOCATION.$NAME))
{
// send browser to success page
header("Location: success.php");
}
}
}
}
}


Once the upload is complete, the script above will redirect the browser to a success page (or an error page, if an error occurred).

Notice in the form that I'm opening a new window when the user clicks the submit button. This new window will show the "be patient" message, and must also keep checking the parent window at pre-defined intervals to see if the transfer is complete. Here's the code:


<html>
<head>
<script language="JavaScript">
<!--
// wait.html
function checkOpenerStatus() {
var strOpener = opener.location.href;
if(strOpener.indexOf("success.php") != -1 ||
strOpener.indexOf("error.php") != -1) {
// I am going to close now
self.close();
}
}
// -->
</script>
</head>
<body onLoad="setInterval('checkOpenerStatus()', 1000)">
<center>
<h1>
Please wait, your upload is being processed!
<br>
This window will close automatically once the upload is complete.
</h1>
</center>
</body>
</html>

This script uses the setInterval() method to check the URL of the parent window every second and, when it detects that the parent has gone to the success or error page (indicating that the upload has completed), it automatically terminates itself with the self.close() method.

And that's about all I have time for. Over the course of this article, I introduced you to JavaScript's four timing functions, showing you how to use the setTimeout() and setInterval() methods to call a function once after a pre-defined delay, or repeatedly at a pre-defined interval. That was the easy part, and I followed it up with a bunch of examples designed to showcase some of the things you can do with this power. Among the example applications I built: a browser tickertape, a countdown clock, a timed slideshow, a variable-speed page object, and a polling status window.

I hope you had fun reading this article, and that the examples sparked off some ideas of where you can use these functions in your own scripts. 'Till next time, see ya!
rohan2kool
i thought he said 'Java', not 'JavaScript'.
ramesh_nim
Java tutorial - starting from fundamentals

u can find

http://java.sun.com/developer/onlineTraining/essentials/
Related topics
Complete Tutorial LINKS for every language
Programming links, info, and tutorials
Java
[JAVA TUTORIALS & FILES] - Java Scripting world
Where to find Java Scripts
Java tutorials
Programming Forum
Google Tips
JAVA Trouble
4 Java Tutorials (Have added a new one.)
Good Java tutorial website? Any1 recommand one?
Constructors in Java, help
I need help with programming...
Java, Eclipse, Android and Web programming tutorials
Reply to topic    Frihost Forum Index -> Miscellaneous -> Tutorials

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.