You Are Here Home > JavaScript

JavaScript

AJAX – Beginner AJAX Tutorial

We are closing down our forums, it’s time to move on, but we are keeping some important threads, here are the AJAX tutorials…

AJAX – Beginner AJAX Tutorial

What you need to know
A basic knowledge of HTML, JavaScript and a server side language.

What is AJAX?
AJAX stands for Asynchronous JavaScript And XML.

XML?!
Don’t worry you don’t need to know XML, in fact we won’t even use XML to write web applications with AJAX.

What data type we will use you are going to see in later tutorials, but I assure you we will use
something 100 times simpler.

Overview
There are a few benefits you can gain by using this technique, one is than you won’t need to send the common parts of the page to the browser whenever a user views a page on your website.

Since this is a beginner AJAX tutorial let’s make a very simple ‘Hello World’ AJAX application.

Step 1:
We are going to use Yahoo! UI library or ‘yui’.
The benefit of using yui is that you don’t need to worry about browser compatibility and also many developers are working on it to make it even better every day.

So go ahead and download the latest version here:
http://developer.yahoo.com/yui/download/

Step 2:
Extract the files and in the ‘build’ folder you will see many folders containing different parts of yui.

For this tutorial we only need yahoo.js, event.js and connection.js
So go ahead and make an HTML file and call it ajax.html (or whatever you want).

Now paste this code into your HTML file:

<html>
<head>
<title>Beginner AJAX Tutorial</title>
 
<script type="text/javascript" src="edit this path to yui/yahoo.js"> </script>
<script type="text/javascript" src="edit this path to yui/event.js"> </script>
<script type="text/javascript" src="edit this path to yui/connection.js"> </script>
 
</head>
<body>
<div id="content">
</div>
</body>
</html>

2 notes:
1. You must edit the path to yui library and be sure the source attribute of your script tags point to the right files.
2. I also added a div to the page so we can display the server’s response in it.

Now we included the portions of yui that we need in our page so let’s write some code.

Step 3:
Now we need to write some code to use yui’s connection object to send requests to the server.

To do this we need to write 2 JavaScript functions to handle 2 situations.
1. Success.
2. Failure, most likely the server didn’t respond.

So lets write our functions, first success:

function success_handler(o) {
document.getElementById('content').innerHTML = o.responseText;
}

The only thing this function does is that it sets the innerHTML of our content container.

2 notes:
1. innerHTML is a non standard attribute that almost all the browsers support.
2. o is an object yui will pass to your functions.

Now lets make our failure handler:

function failure_handler(o) {
document.getElementById('content').innerHTML = 'Server or your connection is death';
}

Here again we change the innerHTML with an appropriate error message.

So all together we have:

<html>
<head>
<title>Beginner AJAX Tutorial</title>
 
<script type="text/javascript" src="yahoo.js"> </script>
<script type="text/javascript" src="event.js"> </script>
<script type="text/javascript" src="connection.js"> </script>
 
<script type="text/javascript">
function success_handler(o) {
document.getElementById('content').innerHTML = o.responseText;
}
 
function failure_handler(o) {
document.getElementById('content').innerHTML = 'Server or your connection is dead';
}
</script>
 
</head>
<body>
<div id="content">
</div>
</body>
</html>

Let’s go ahead and write two more functions, one for sending a request to the server and one for trying the failure situation.

Here we go:

function send_request() {
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.php', callback);
}

This is a simple function that sends an asynchronous request to the server.

Let’s take a look at it in more detail:

1. We defined a callback object which sets our success_handler and failure_handler functions for success and failure situations respectively
and also we define a timeout for the connection. This timeout is in milliseconds, so we are setting it to 10 seconds.
This means if we receive a response within 10 seconds then yui calls our success_handler function, otherwise it calls failure_handler.

2. The second line is the actual request. asyncRequest method will handle everything and calls our callback functions.
We are passing 3 parameters.

First parameter is the type of request, which is GET here because we are not sending any form data to the server. (I will show you POST requests in later tutorials)

Second parameter is the URL which we want to send the request to.

Third parameter is our callback object.

Now let’s make another function to test the failure situation:

function test_failure() {
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/some-file-that-doesnt-exists.php', callback);
}

This function is the same except it sends a request to a non-existing file, so it’s going to fail.

So far we have this:

<html>
<head>
<title>Beginner AJAX Tutorial</title>
 
<script type="text/javascript" src="yahoo.js"> </script>
<script type="text/javascript" src="event.js"> </script>
<script type="text/javascript" src="connection.js"> </script>
 
<script type="text/javascript">
function success_handler(o) {
document.getElementById('content').innerHTML = o.responseText;
}
 
function failure_handler(o) {
document.getElementById('content').innerHTML = 'Server or your connection is death';
}
 
function send_request() {
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.php', callback);
}
 
function test_failure() {
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/some-file-that-doesnt-exists.php', callback);
}
</script>
 
</head>
<body>
<a href="javascript:send_request();">Send Request</a> | <a href="javascript:test_failure();">Fail a request</a>
<div id="content">
</div>
</body>
</html>

Note: I added the line:

<a href="javascript:send_request();">Send Request</a> | <a href="javascript:test_failure();">Fail a request</a>

To be able to test our little application.

Go ahead and try it here:

http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.html

And the PHP file is only 3 lines:

<?php
echo 'Hello World!';
?>

That’s it for now.
Thanks and good luck!
-Codehead

Next: AJAX – Beginner AJAX Tutorial – Display a Progress Bar or a Loading Message

AJAX – Beginner AJAX Tutorial
Comments (6)   Filed under: AJAX, JavaScript, PHP, Web Development, yui   Posted by: Codehead

Fixing markItUp layout issues in some browsers…

markItUp is a cool little text editor and the nice thing about it is that it’s very simple and light weight.

I had some layout issues in Gecko and Webkit browsers and the way to fix it is this:

1 – Go to:
/markitup/skins/markitup

2 – Open style.css and find:

.markItUpEditor {
	font:12px 'Courier New', Courier, monospace;
	padding:5px 5px 5px 35px;
	border:3px solid #3C769D;
	width:643px;
	height:320px;
	background-image:url(images/bg-editor.png);
	background-repeat:no-repeat;
	clear:both; display:block;
	line-height:18px;
	overflow:auto;
}

3 – Replace the it it with:

.markItUpEditor {
	font:12px 'Courier New', Courier, monospace;
	padding:5px;
	border:1px solid #AAAAAA;
	width: 275px;
	height: 150px;
	line-height:18px;
	overflow:auto;
}

I hope this helps someone…

Fixing markItUp layout issues in some browsers…
Comments (1)   Filed under: JavaScript, Web Design, Web Development, jQuery   Posted by: Codehead

A JavaScript/jQuery News Ticker

I know I haven’t posted anything lately, I have been busy which is a good thing but I couldn’t resist this one, here is a simple news ticker using JavaScript and the great jQuery library.

Here is the example:
http://images.code-head.com/code/javascript/jquery-news-ticker.html

I know you might be able to write this using objects in a nicer form but this will work and it’s to demonstrate the idea…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery New Ticker</title>
 
	<script type="text/javascript" src="http://images.code-head.com/jquery/jquery.js"> </script>
 
   <script type="text/javascript">
		$(document).ready(function() {
			var current = -1;
			var elems = new Array();
			var elems_i = 0;
			$('.items').each(function() {
				elems[elems_i++] = $(this);
			});
			var num_elems = elems_i - 1;
			var animate_out = function() {
				elems[current].animate({ top: '-100px' }, 'fast', 'linear', animate_in);
			}
			var animate_out_delay = function() {
				setTimeout(animate_out, 1000); /****************************** Change 1000 to make it longer/shorter/whatever */
			}
			var animate_in = function() {
				current = current < num_elems ? current + 1 : 0;
				elems[current].css('top', '200px').animate({ top: '0px' }, 'fast', 'linear', animate_out_delay);
			}
			animate_in();
		});
	</script>
 
   <style type="text/css">
		.ticker {
			position: relative; /* So we can absolute the .items */
			width: 400px;
			height: 100px;
			overflow: hidden;
			margin: 100px;
			border: 1px dashed #666666;
		}
		.items {
			position: absolute;
			top: 200px;
			margin: 10px;
		}
	</style>
 
</head>
 
<body>
 
   <div class="ticker">
      <div class="items">I'm a Cool</div>
      <div class="items">JavaScript</div>
      <div class="items">News Ticker</div>
      <div class="items">Using jQuery</div>
      <div class="items">For Smooth</div>
      <div class="items">And Nice</div>
      <div class="items">Animation</div>
      <div class="items">By Hamid Alipour</div>
      <div class="items">@ <a href="http://blog.code-head.com" target="_blank">blog.code-head.com</a></div>
   </div>
 
</body>
</html>

Again, the code is straight forward, you must be able to understand what happens but here is a little explanation.

<div class=”items”> … </div> are the news headlines to be animated and using CSS, they are absolute-positioned somewhere under the parent <div class=”ticker”> … </div> box.

Normally, .itmes would be visible under the box, even when they are absolute-positioned but if you look into the stylesheet you will see:

.ticker {
   ...
   width: 400px;
   height: 100px;
   overflow: hidden;
   ...
}

That will prevent this from hapenning, so now our .items are floating somewhere under the box which is what we want. (Change it’s ‘width’ and ‘height’ to fit in whatever space you want…)

The JavaScript code starts with the first one and animates it all the way to the top and then pauses for a second (you can change it to whatever time you want), then it animates the one on the top to the top of the box by animating it all the way to ‘top: -100px;’, note that the same ‘overflow: hidden;’ prevents it from showing.

It then picks up the next item, sets it’s top to 200px and animates it all the way to the top again and then repeat forever.

You might ask why it’s first setting the .items top to 200px; it’s because we are animating them to top of the box so we have to set their top to 200px again each time (we did this first in CSS), this is not important in the first iteration but after that every single item is on top of the box and has to be moved under the box.

I hope this makes sense.

A JavaScript/jQuery News Ticker
Comments (0)   Filed under: JavaScript, jQuery   Posted by: Codehead

Scroll To Top Of The Page

Here is the simple function call that does this:

scroll(0, 0);

So you could have a link like this:

<a href="javascript:scroll(0, 0);">Back To Top</a>
Scroll To Top Of The Page
Comments (0)   Filed under: JavaScript   Posted by: Codehead

Basic threading in JavaScript; multiple threads of execution in JavaScript

I was searching the web yesterday for this and didn’t really find a simple way of doing this and suddenly, I remembered something.

It’s extremely simple, someone could build on it with all sorts of features but for now, here is an example:
http://images.code-head.com/code/javascript/js-threads.html

As you can see there are two counters, one is counting up and the other down simultaneously.

Here is the start_thread function:

             function thread_start(callback) {
		setTimeout(callback, 1);
		return true;
	}

The trick is that setTimeout *does not* block the execution ;)

I hope this helps someone :)

Basic threading in JavaScript; multiple threads of execution in JavaScript
Comments (2)   Filed under: Fun, General, JavaScript, Programming, jQuery   Posted by: Codehead

How to fix transparent PNGs in Internet Explorer

You might know already that there are some issues with transparent GIFs but PNGs don’t have those issues.
The problem with transparent PNGs is that Internet Explorer doesn’t like them so much and gives them a funny background.

So here is the solution that works great:
http://homepage.ntlworld.com/bobosola/index.htm

How to fix transparent PNGs in Internet Explorer
Comments (0)   Filed under: Annoying Stuff, JavaScript, Web Browsers, Web Design, Web Development   Posted by: Codehead

Calling a JavaScript function from Actionscript 3 (Flash)

It’s very easy:

import flash.external.ExternalInterface;
...
ExternalInterface.call("your_javascript_function()");

You can even get a return value:

var x:int = ExternalInterface.call("get_x()");

To pass an argument try:

var retval:int = ExternalInterface.call("some_js_function()", "the-argument");
Calling a JavaScript function from Actionscript 3 (Flash)
Comments (35)   Filed under: Actionscript, Flash, JavaScript, Web Development   Posted by: Codehead

iGoogle uses yui (Yahoo User Interface Library)

Funny, I would imagine that they have developed an in house JavaScript library by now but this is great, using a well maintained and good library is a great programming practice.

You can check it out here:
http://www.google.com/ig
(Right click and view the source)

Yes, I have to see the source code for everything I can find :)

I personally can’t imagine living without jQuery, I used yui for a long time but jQuery is a beautiful piece of engineering.

yui is still great and has so many components but it’s not my type, I’m lazy ;)

iGoogle uses yui (Yahoo User Interface Library)
Comments (0)   Filed under: JavaScript, jQuery, yui   Posted by: Codehead

Users without JavaScript and what to do about them

Here is what I do:

<noscript>
	<div style="color:#FF0000;">
   	<strong>Sorry!</strong><br /><br />
      Please enable JavaScript on your browser to be able to use advanced features of this site.
      <br /><br /><br />
      <strong>Internet Explorer 6 or 7</strong>
      <ul style="list-style-type: decimal;">
      	<li>Click the Tools menu.</li>
         <li>Select Internet Options.</li>
         <li>Click the Security tab.</li>
         <li>Click the Custom Level button.</li>
         <li>Scroll down until you see the 'Scripting' section. Select the 'Enable' radio button for 'Active Scripting.'</li>
         <li>Click the OK button.</li>
         <li>Click the Yes button in the confirmation window.</li>
      </ul><br />
      <strong>Firefox 2 or 3</strong>
      <ul style="list-style-type: decimal;">
      	<li>Click the Tools menu.</li>
         <li>Select Options.</li>
         <li>Click the Contents tab.</li>
         <li>Select the 'Enable JavaScript' checkbox.</li>
         <li>Click the OK button.</li>
      </ul><br />
      <strong>Safari 2 or 3</strong>
      <ul style="list-style-type: decimal;">
      	<li>Click the Safari menu.</li>
         <li>Select Preferences.</li>
         <li>Click the Security tab.</li>
         <li>Select the 'Enable JavaScript' checkbox.</li>
      </ul>
   </div>
</noscript>

“noscript” tag ensures that users without JavaScript will see this message ;)

Users without JavaScript and what to do about them
Comments (0)   Filed under: AJAX, JavaScript, Web Development   Posted by: Codehead

jEditable and password input type support

I wrote a post earlier about how jEditable (a jQuery) plugin needed password support and the author of the plugin wrote back and said here is how to add this feature:

$.editable.addInputType(’password’, {});

You can read more here:
http://www.appelsiini.net/2007/8/custom-input-types
http://www.appelsiini.net/2008/4/autogrow-textarea-for-jeditable

This plugin is really great and we are doing some exciting things on Bloggapedia with it.
We will launch early this week hopefully because we are working on a recommendation engine.

Happy Coding :)

jEditable and password input type support
Comments (0)   Filed under: AJAX, JavaScript, Projects, Web Development   Posted by: Codehead
« Newer PostsOlder Posts »