Présentation de JSON

43
Présentation de JSON JSON (JavaScript Object Notation – Notation Objet issue de JavaScript) est un format léger d'échange de données. Il est facile à lire ou à écrire pour des humains. Il est aisément analysable ou générable par des machines. Il est basé sur un sous-ensemble du langage de programmation JavaScript (JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999 ). JSON est un format texte complètement indépendant de tout langage, mais les conventions qu'il utilise seront familières à tout programmeur habitué aux langages descendant du C, comme par exemple : C lui-même, C++, C#, Java, JavaScript, Perl, Python et bien d'autres. Ces propriétés font de JSON un langage d'échange de données idéal. JSON se base sur deux structures : Une collection de couples nom/valeur. Divers langages la réifient par un objet, un enregistrement, une structure, un dictionnaire, une table de hachage, une liste typée ou un tableau associatif. Une liste de valeurs ordonnées. La plupart des langages la réifient par un tableau, un vecteur, une liste ou une suite. Ces structures de données sont universelles. Pratiquement tous les langages de programmation modernes les proposent sous une forme ou une autre. Il est raisonnable qu'un format de données interchangeable avec des langages de programmation se base aussi sur ces structures. En JSON, elles prennent les formes suivantes : objet {} { membres } membres chaîne : valeur membres , chaîne : valeur tableau [] [ éléments ] éléments valeur éléments , valeur valeur chaîne nombre objet tableau true false null chaîne "" " caractères " caractères caractère caractères caractère caractère tout-Unicode-sauf-"-ou-\-ou-contrôle \" \\ \/ \b \f \n \r \t \u quatre-chiffres-hexa nombre entier entier frac entier exp entier frac exp entier chiffre chiffre1-9 chiffres - chiffre - chiffre1-9 chiffres frac . chiffres exp e chiffres chiffres chiffre

Transcript of Présentation de JSON

Page 1: Présentation de JSON

Présentation de JSONJSON (JavaScript Object Notation – Notation Objet issue de JavaScript) est un format léger d'échange de données. Il est facile à lire ou à écrire pour des humains. Il est aisément analysable ou générable par des machines. Il est basé sur un sous-ensemble du langage de programmation JavaScript (JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999). JSON est un format texte complètement indépendant de tout langage, mais les conventions qu'il utilise seront familières à tout programmeur habitué aux langages descendant du C, comme par exemple : C lui-même, C++, C#, Java, JavaScript, Perl, Python et bien d'autres. Ces propriétés font de JSON un langage d'échange de données idéal.

JSON se base sur deux structures :

Une collection de couples nom/valeur. Divers langages la réifient par un objet, un enregistrement, une structure, un dictionnaire, une table de hachage, une liste typée ou un tableau associatif.

Une liste de valeurs ordonnées. La plupart des langages la réifient par un tableau, un vecteur, une liste ou une suite.

Ces structures de données sont universelles. Pratiquement tous les langages de programmation modernes les proposent sous une forme ou une autre. Il est raisonnable qu'un format de données interchangeable avec des langages de programmation se base aussi sur ces structures.

En JSON, elles prennent les formes suivantes :

Un objet, qui est un ensemble de couples nom/valeur non ordonnés. Un objet commence par { (accolade gauche) et se termine par } (accolade droite). Chaque nom est suivi de : (deux-points) et les couples nom/valeur sont séparés par , (virgule).

Un tableau est une collection de valeurs ordonnées. Un tableau commence par [ (crochet gauche) et se termine par ] (crochet droit). Les valeurs sont séparées par , (virgule).

Une valeur peut être soit une chaîne de caractères entre guillemets, soit un nombre, soit true ou false ou null, soit un objet soit un tableau. Ces structures peuvent être imbriquées.

Une chaîne de caractères est une suite de zéro ou plus caractères Unicode, entre guillemets, et utilisant les échappements avec antislash. Un caratère est représenté par une chaîne d'un seul caractère.

objet{}

{ membres }membres

chaîne : valeur membres , chaîne : valeur

tableau[]

[ éléments ]éléments

valeur éléments , valeur

valeurchaîne nombreobjettableautruefalsenull

chaîne""

" caractères "caractères

caractèrecaractères caractère

caractèretout-Unicode-sauf-"-ou-\-ou-contrôle\"\\\/\b\f\n\r\t

\u quatre-chiffres-hexanombre

entierentier fracentier expentier frac exp

entierchiffrechiffre1-9 chiffres - chiffre- chiffre1-9 chiffres

frac. chiffres

expe chiffres

chiffreschiffrechiffres chiffre

eee+e-EE+E-

Page 2: Présentation de JSON

Mis à part quelques détails d'encodage, voilà qui décrit le langage dans son intégralité.

Une chaîne de caractères est très proche de ses équivalents en C ou en Java. Un nombre est très proche de ceux qu'on peut rencontrer en C ou en Java, sauf que les formats octal et hexadécimal ne sont pas utilisés.

De l'espace blanc est autorisé entre tous lexèmes.

Page 3: Présentation de JSON

Introduction to JSON and PHPBy Frank Lakatos May 24, 2009

So you've heard the fanfare over JSON, but still haven't had the opportunity to dive into using it. Well, as a matter of fact, you may have been using JSON all along and not known it. Compounded by the fact that since PHP 5.2 there is native support for JSON, learning how to send data between your client and your server just got a whole lot easier.

What is JSON?JSON, or JavaScript Object Notation, has been getting a large amount of attention recently in the IT world. This is mostly powered by its extremely lightweight implementation, its common usage in APIresponses, and its already native support in JavaScript. JSON isn't simply a way to code objects in JavaScript, but it is the actual form that a JavaScript engine will map the object to in memory. In short, it is an extremely fast and powerful way of transporting data between two interfaces.

How does it work?JSON is capable of setting up data constructs for integers, strings, arrays, and booleans - the most essential data building blocks. Using a carefully defined syntactical construct, JSON can be used to outline an object and with the use of javascript's eval() function, they can be converted to a working object. 

But the power does not end there. Other popular programming languages have been implementing native support for JSON, such as PHP and ActionScript. For example, PHP can now convert an associative array of data into a JSON string by using the new json_encode() function, provided in version 5.2+ of the language. For languages without native support, you can find a full range of implementation classes available at the JSON website.

The Syntax: explained

Declaration

All JSON objects are declared with a pair of curly braces. You can assign them to a variable like you would any other data structure.

1. var myObj = {}

That's it! While not very powerful, this is all that's required to create objects using JSON. So let's start adding some properties to this object. 

Page 4: Présentation de JSON

Strings

We are going make this object represent me, so let's start by adding my name.

1. var myObj = {name: 'Frank'}

Let's take a second to carefully look at what we did here. We wanted to add a property called "name", and to do so, you simply write the property, "name". We follow the property label by a colon to separate the property name and its value. To the right of the colon, comes the value. Since we wanted the value to be a string, we put it in quotes.

With the JSON we have put in place, you are now able to access the property by using the dot notation. To access a property, follow the "Variable [dot] property" construct.

1. alert(myObj.name) // "Frank"

Integers

If we wanted to assign a property to the object of an integer data type, there is no need to quote the value.

1. var myObj = {age: 24}

Multiple properties are separated by a comma.

1. var myObj = {name: 'Frank', age: 24}2. alert("My name is " + myObj.name + " and I'm " + myObj.age);3. // "My name is Frank and I'm 24

Booleans

Like integers, booleans are also unquoted

1. var myObj = {name: 'Frank', age: 24, engaged: true}

Arrays

Arrays can contain a collection of the previously mentioned data types. To define an array, wrap the value in square brackets and separate the values with commas.

Page 5: Présentation de JSON

Note: I will now add line breaks and indentation for legibility. It has no bearing on the working order of the object.

1. var myObj = {2.     name: 'Frank',3.     age: 24,4.     engaged: true,5.     favorite_tv_shows: ['Lost', 'Dirty Jobs', 'Deadliest Catch', 'Man vs Wild']6. }

You can access a value in an array in the object by using a combination of the dot notation (to access the objects property) and index notation (to access an indexed value of an array).

1. alert(myObj.favorite_tv_shows[1]); // "Dirty Jobs"

To take the array complexity one step further, an array can also contain other objects.

1. var myObj = {2.     name: 'Frank',3.     age: 24,4.     engaged: true,5.     favorite_tv_shows: ['Lost', 'Dirty Jobs', 'Deadliest Catch', 'Man vs Wild'],6.     family_members: [7.         {name: "Frank", age: 57, relation: "father"},8.         {name: "Tina", age: 26, relation: "sister"}9.     ]10. }

This still requires dot and index notation, with an additional dot notation for accessing the property of the object found in the indexed array value.

1. alert(myObj.family_members[1].name) // "Tina"

There is one situation where you will use square brackets to access an objects property and not the dot notation: when you are using a variable as the property name. For example:

1. var myObj = {2.     name: 'Frank',3.     age: 24,4.     engaged: true,5.     favorite_tv_shows: ['Lost', 'Dirty Jobs', 'Deadliest Catch', 'Man vs Wild'],6.     family_members: [7.         {name: "Frank", age: 57, relation: "father"},8.         {name: "Tina", age: 26, relation: "sister"}9.     ]10. }11.  12. var property = "age"13.  14. alert(myObj[property]); // "24"

Recap

Take some time experimenting with JSON and you will see that you can pick up the concept and syntax rather quickly. As a caveat that may save you time in the future: certain languages require you to quote the property names, such as ActionScript. If not, it will complain.

Page 6: Présentation de JSON

1. myObj = {name: "Frank"} // will complain2. myObj = {"name": "Frank"} // will work

Next, I will demonstrate how JSON is commonly used in API calls.

Loading External JSON into your ApplicationFor our example, we are going to use the Twitter API. For those of you who haven't tried to interface with Twitter, it is extremely easy to comprehend. Let's say that you absolutely adore me. So much, in fact, that you would love to put my latest tweets on your very own web site. Bless your heart.

Step 1 - Get the Object

If you look over the Twitter API, you can read over all of the wonderful method calls they provide for you, including one that lets you retrieve a user's timeline in JSON format. The format of the URI is as follows:

http://twitter.com/statuses/user_timeline/franklakatos.json

If you try to load this URI in your browser, it will prompt you to download a file. Why a file, and what is inside of it? Since JSON is a front-end technology, it would violate Cross-Site Scripting (XSS) rules to make calls to another domain using the XMLHttpRequest object, the object that powers other asynchronous calls as with AJAX. To work around doing this, you will include this file call in your HTML as a javascript include file:

1. <script type="text/javascript"2. src="http://twitter.com/statuses/user_timeline/franklakatos.json">3. </script>

The API request commonly makes available a varying number of parameters to control the output of your request, such as a limit to how many to return.

1. <script type="text/javascript"2. src="http://twitter.com/statuses/user_timeline/franklakatos.json?count=1">3. </script>

If you make a call to this JSON file, you will be returned a file that contains an object that looks like this:

1. [{2. "text":"Just handed in my last project ever for my masters, all I have now is

finals next week. Goodbye, school. Hello, life.",3. "in_reply_to_screen_name":null,4. "user":{5. "profile_background_color":"9ae4e8",6. "followers_count":10,7. "profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production\/

profile_images\/110871907\/me_copy_normal.jpg",8. "description":null,9. "utc_offset":null,10. "friends_count":6,11. "profile_text_color":"000000",

Page 7: Présentation de JSON

12. "screen_name":"franklakatos",13. "following":null,14. "profile_background_image_url":"http:\/\/static.twitter.com\/images\/themes\/

theme1\/bg.gif",15. "profile_link_color":"0000ff",16. "url":null,17. "name":"franklakatos",18. "favourites_count":0,19. "protected":false,20. "profile_sidebar_fill_color":"e0ff92",21. "time_zone":null,22. "profile_sidebar_border_color":"87bc44",23. "profile_background_tile":false,24. "location":null,25. "id":18163247,26. "notifications":null,27. "statuses_count":67,28. "created_at":"Tue Dec 16 14:44:59 +0000 2008"29. },30. "truncated":false,31. "in_reply_to_status_id":null,32. "in_reply_to_user_id":null,33. "id":1731244194,34. "favorited":false,35. "source":"<a href=\"http:\/\/twitterfon.net\/\">TwitterFon<\/a>",36. "created_at":"Thu May 07 21:36:12 +0000 2009"37. }]

Look at all that great content! A quick glance will show that the object is an array of objects (notice the string begins and ends with square brackets). Therefore, if we assigned this string to a variable myTweets, we can access our first object with myTweets[0], for instance.

Here are some examples of accessing the data:

1. myTweets[0].text // "Just handed in my last project ever for ..."2. myTweets[0].created_at // "Thu May 07 21:36:12 +0000 2009"3. myTweets[0].user.name // "franklakatos"

Step 2 - Access the Data Using Callbacks

The astute reader may have noticed that the object included in the API file has no variable assigned to it, and since we include the JSON object in an external javascript file, there is no way for us to assign one to it. So how are we suppose to access this data?

The answer, callbacks. Most APIs using JSON will implement a callback system, where you tell it a name of one of your functions and when your site is done downloading the JSON file, it will automatically call that function and pass the object as an argument. 

1. <script type="text/javascript"2. src="http://twitter.com/statuses/user_timeline/franklakatos.json?

callback=cb&count=1">3. </script>

Inside your function, you can assign it to a variable, use the data as needed, et cetera. All you need to do is

Page 8: Présentation de JSON

create the function with one parameter, which will be used to pass the object along.

1. var myTweets;2. function cb(data){3.     myTweets = data;4. }

Now you can access the objects data whenever you would like, using the myTweets global variable. Here is an example of how you can implement the Twitter API to use in production:

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">4. <head>5. <title>Twitter API w\ JSON</title>6. <script type="text/javascript">7. var myTweets8. function cb(data){9.     myTweets = data;10.     document.write(myTweets[0].user.name + " says:<br/>\"" + myTweets[0].text +

"\"");11. }12. </script>13. <script type="text/javascript"14. src="http://twitter.com/statuses/user_timeline/franklakatos.json?

callback=cb&count=1">15. </script>16. </head>17. <body>18. </body>19. </html>

...which would output..

1. franklakatos says:2. "Just handed in my last project ever for my masters, all I have now is finals next

week. Goodbye, school. Hello, life."

Next, we will get into the true power of using JSON: implementing client and server communication.

Client / Server Data Retrieval With JSONNow that you are well versed with the concepts and syntax of JSON, and you have a working example of how to use JSON for client-side API communication, let's see how we can take advantage of server-side technologies to transfer data between the client and the server.

Until recently, the world of asynchronous communication was ruled by XML. While in production successfully, XML is still an extremely bulky language, increasing data transfer overhead. Perhaps its biggest downfall, however, is that XML is commonly generated by server languages who many times do not have an XML converter, requiring manual conversion. Then, they are delivered to client languages, most notably JavaScript, who also do not have native support for XML. It would make more sense, for code simplicity and maintenance, for everyone to speak the same language.

Page 9: Présentation de JSON

Using PHP with JSON

Mentioned earlier, as of PHP 5.2, there is native support for encoding and decoding JSON using json_encode() andjson_decode(), respectively. That means that you can now create JSON strings in PHP files, allow JavaScript to make calls to the file, have JavaScript manipulate the object and send it back to PHP, all in the same notation!

Getting Started

We are going to create a PHP file that will output JSON in the same manner as the Twitter API call. Since the PHP file will be hosted on the same domain as the HTML file, we can then make an asynchronous request to the object to load to the page. 

If you stop and think about the difference between and JSON and a PHP associative array, you will notice they are extremely similar: they both represent the same data types in the same manner, and they both have a specific syntax for doing so. Therefore, to create a JSON object in PHP, you will simply create an associative array in the same manner as usual. When you are finished creating the array, you will pass the array into the json_encode() function, and it will take care of updating the syntax.

1. <?php2. $myTweets = array(3.     "text" => "Just handed in my last project ever ".4.         "for my masters, all I have now is finals ".5.         "next week. Goodbye, school. Hello, life.",6.     "created_at" => "Thu May 07 21:36:12 +0000 2009"7. );8.  9. $myJSONTweets = json_encode($myTweets);10.  11. echo $myJSONTweets;12. #{"text":"Just handed in my last project ever for my masters, all I have now is

finals next week. Goodbye, school. Hello, life.",13. #"created_at":"Thu May 07 21:36:12 +0000 2009"14. #}15. ?>

The only other data type to account for is including object in an associative array, but this is also trivial. Simply create another associative array and add it as a value to the main associative array.

1. <?php2. $myTweets = array(3.     "text" => "Just handed in my last project ever ".4.         "for my masters, all I have now is finals ".5.         "next week. Goodbye, school. Hello, life.",6.     "created_at" => "Thu May 07 21:36:12 +0000 2009"7. );8.  9. $myTwitterUser = array("name" => "franklakatos");10. $myTweets['user'] = $myTwitterUser;11. $myJSONTweets = json_encode($myTweets);12.  13. echo $myJSONTweets;14. #{"text":"Just handed in my last project ever for my masters, all I have now is

finals next week. Goodbye, school. Hello, life.",15. #"created_at":"Thu May 07 21:36:12 +0000 2009",

Page 10: Présentation de JSON

16. #"user":"{"name":"franklakatos"}"17. #}18. ?>

The JavaScript Call

In similar fashion as before, we need to have JavaScript access an external file to get a JSON object. While before we embedded a script tag to avoid the limitation of same-domain access with the XMLHttpRequest object, we can now take advantage of the asynchronous call as we are hosting the PHP file.

Note: I will be using jQuery to help us out with the XMLHttpdRequest

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">4. <head>5. <title>Twitter API w\ JSON</title>6. <script type="text/javascript" src="http://www.google.com/jsapi"></script>7. <script type="text/javascript">8. // Load jQuery9. google.load("jquery", "1.3");10. </script>11. <script type="text/javascript">12. $(function(){13.     //Get the JSON string and pass it to the cb function14.     $.get("twitter.php", function(data){cb(data)});15. })16.  17. function cb(data){18.     //converts the JSON string to a JavaScript object19.     eval("myTweets="+data);20.     myTweets = dataToObj;21.     document.write(myTweets.user.name + " says:<br/>\"" + myTweets.text + "\"");22. }23. </script>24. </head>25. <body>26. </body>27. </html>

Perhaps the most confusing part of all of this is the use of the eval() function. The eval function takes a string and executes it like it is code. When we receive JSON from PHP, it is simply a string that is notated as a JavaScript object, but it is not yet a JavaScript object. It is up to JavaScript to take this string and covert it to an object. That is what eval() is used for, and as you can see we assigned it to the variable name myTweets.

Going Back to the Server

So let's say you have a system in place that allows you to update the text property and PHP will update Twitter accordingly. That means we can update the object that PHP originally provided us with, update the values of some properties, and send it back to PHP.

Page 11: Présentation de JSON

1. myTweets.text = "My New Text"

When you finish with updates such as the former, you can then serialize the object back into a JSON string and send it in a POST request back to PHP. There are many jquery plugins to do this, or if you prefer a little lower level, JSON.org offers a parser for the converting.

1. //implements the JSON.org parser2. mySerializedTweets = JSON.stringify(myTweets);3. $.post("twitter.php",{page: submit, obj: mySerializedTweets});

Now, PHP can receive the JSON string and convert it back into the associative array you started with.

1. $myTweets = json_decode($_POST['obj']);

http://www.itnewb.com/tutorial/Introduction-to-JSON-and-PHP

Page 12: Présentation de JSON

Beginners Guide to JavaScript Objects, Methods and AttributesBy Frank Lakatos Mar 24, 2009

In this article we'll be taking a look at JavaScript objects, methods, attributes and detailing how Object Oriented Programming can help you write your own software libraries. I'll be explaining what objects, methods and attributes are and showing you how to objectify your JavaScript so you'll only have to maintain one code base per functionality which will allow you to reuse your code over and over in many different projects.

IntroductionIn this article we'll be taking a look at JavaScript objects, methods, attributes and detailing how OOP can help you write your own software libraries. I'm not only going to explain what objects, methods and attributes are but I'll also be showing you how to objectify your JavaScript so you'll only have to maintain one code base per functionality which will allow you to reuse your code over and over in many different projects.

What are Objects, Methods and Attributes?

An object is literally a representation of an object in real life. Every object has characteristics known as attributes, and certain abilities or functionality known as methods or procedures -- the classic example being a car.

The car object has some attributes such as make, model, color and so on. It also has some methods such as start, drive, stop and turn. If a car is an object, the JavaScript class would be the blueprints for making the object. We write classes that define what attributes and methods an object should have, and when we "instantiate" the class we initializeit and get a usable version of the object. To put it in terms of our example, we create a blueprint for the car that specifies its color, dimensions and what abilities it should have.

Simple Example

In JavaScript, everything is an object, and objects always have attributes and properties tied into them. As a quick example to how objects work, let's look at an array.

1. arrMusic = new Array();

What that literally says is, "I want to create an Array object and name it arrMusic". Well, JavaScript has a class or "blueprint" for arrays. One of the attributes or "characteristics" of an array is its "length" -- the number of items stored in the array. You access an objects attributes by using the dot-notation of objectname.attribute.

Page 13: Présentation de JSON

1. var numItems = arrMusic.length;2. document.write(numItems);3. // outputs 0 -- as the array is currently empty

The array object also has methods or "capabilities" such as toString(), which will take the values of the array and convert them into a comma separated string. You call methods in nearly the same way you would attributes -- by using the dot-notation of objectname.method(). So now let's add a few elements to our array and convert it into a string.

1. arrMusic[0] = "Jazz";2. arrMusic[1] = "Rock";3. arrMusic[2] = "Hip-Hop";4.  5. var stringFromArray = arrMusic.toString();6. document.write(stringFromArray);7. // outputs "Jazz,Rock,Hip-Hop"

So there you go, that's an object in JavaScript. You've probably been using them all along and just didn't realize it -- now you do. Wouldn't it be cool if you could write your own, specific to what you need, and be able to call them just as effortlessly? You can, and you're about to learn how to do it.

Object Requirements and Class Blueprints

One of the most important aspects of writing a class for an object is figuring out what your object is. I know, it sounds silly but seriously -- we're often not so fortunate to be creating an object as trivial as a Car. So, let's take a look at a simple scenario.

Alright, let's say a client calls you up and he or she needs an application created. The application should have 5 buttons that a) draw a box on the screen; b) increase the size of the box; c) decrease the size of the box; d) change the color of the box; and e) remove / hide the box.

In this scenario the client is talking about manipulating an HTML element -- more specifically, they're talking about interfacing with the HTML through the DOM via a client-side scripting language. In our case that client-side scripting language is JavaScript.

All semantics aside, let's say the element will be a <div> (but, it doesn't have to be). We can create a "box" object that will be a representation of the <div> element in the browser. When we need to interface with the element we can talk to the Box object, which will control the attributes and methods of the actual element through the DOM which interfaces the web browser.

Page 14: Présentation de JSON

Collecting the Requirements

Let's recap the requirements of the scenario application.

1. Create a box

2. Make the box bigger

3. Make the box smaller

4. Change the color of the box

5. Remove the box

As you look over these requirements, you may say to yourself "hey, I could use this functionality on half a dozen other projects". Well, what we're soon to do is package this functionality into a box object that we can reuse. If you get in the habit of programming this way you'll begin to find you have many reusable objects that can be merged together into a software library.

Determining the Blueprints for the Class

Next up, we need to determine what our Box object entails as far as attributes and methods go. So, let's examine each of the requirements and start pulling things together.

1. Create a box

What do boxes have, how can we create one? Well, we know a box has a width and height so there are 2 attributes. The box also needs a color, so that will be another. We access HTML elements via document.getElementById() so we'll have to assign it a unique ID so there we have the 4th attribute.

In this scenario those are the only attributes we need to concern ourselves with. Anything else you can think of to describe the box would also be an attribute, such as a border width, a border color, opacity and so on.

So the attributes are known, and we also know we'll need to write a method (function) to actually show the box -- think back to the car example, showing the box might be the equivalent of starting the car. We can show the box by setting the HTML <div> elements CSS display attribute to the value "block".

1. // assuming <div id="box">2. // example setting display attribute -- show <div>3. document.getElementById('box').style.display = 'block';

We'll get into writing the actual object and methods here in a bit.

2. Make the box bigger

This is an example of a method, it doesn't describe the box, it describes what the box can do. So we need a method to make the box bigger, and that can be done by adjusting the "<div>"s CSS width and height attributes.

1. // example setting width and height attributes2. document.getElementById('box').style.width = '100px';3. document.getElementById('box').style.height = '100px';

3. Make the box smaller

Page 15: Présentation de JSON

Decreasing the size of the box will work just as step #2, but instead of doing a little math to increase it we'll be doing a little math to decrease it.

4. Change the color of the box

Also an ability of the box, so we'll need to create another method to handle this functionality. We can change the color by modifying the "<div>"s CSS backgroundColor attribute.

1. // example changing the CSS backgroundColor attribute2. document.getElementById('box').style.backgroundColor = 'red';

5. Remove / hide the box

Finally we'll need a method to hide the box and this can be done by setting the "<div>"s CSS display attribute to none.

1. // example setting display attribute -- hide <div>2. document.getElementById('box').style.display = 'none';

Let's Continue

Alright, now that we've spent a little time learning about objects and took a closer look at the requirements of our scenario we're ready to actually create the Box object.

o Attributes: Height, Width, Color, DOM ID

o Methods: makeBox(), makeBigger(), makeSmaller(), changeColor(), unmakeBox()

Continue with Creating the Box Object ➜.

Creating the Box ObjectWhat's important to keep in mind while implementing a class are the differences between what should be included in the class and what should be included in the client code. As a rule of thumb, keep all the specifics out of the class or make the specifics in a class adjustable by the client. The closer you adhere to that, the more flexible the class will be.

Creating the Class -- Attributes

To create a class, you simply create a function. It's a good idea to use a name for the class indicative of the fact it's actually a class to create an object. I normally tend to stick to a naming convention along these lines.

1. function BoxObj() {2.     // attributes and methods go in here

Page 16: Présentation de JSON

3. }

Tada! That's a simple class -- I know, it's pretty lame but it's still a class. We can instantiate the class in the same way we instantiated a "new Array" earlier.

1. // class code2. function BoxObj() {3.     // attributes and methods go in here4. }5.  6. // client code -- instantiates class for use7. box = new BoxObj();8.  9. // box is now an "instance" of the the BoxObj object

Next up, let's populate our object with the attributes we discussed -- namely width, height and DOM ID. You'll notice I prepend the reserved word "this" (self reference to our object) to the attributes using dot-notation. This tells JavaScript to add the attribute (such as color) to our object, and you'll find that all properties and methods inside an object are referenced in this way. Note I said "inside the object", as the objects name is used when outside the object.

In the event you're really new to this stuff, note the object accepts 3 parameters (domId, width and height) and when we instantiate the class we pass these parameters.

1. function BoxObj(domId, width, height){2.     this.domId = '';3.     this.width = 0;4.     this.height = 0;5.     this.color = "red";6.  7.     // our methods will go here8. }9.  

10. box = new BoxObj('box', 100, 100);

In the same way we called the length attribute of an Array we can now call the box attributes.

1. var box = new BoxObj();2. document.write(box.color);3. // outputs "red"

Hard-coding the initial attribute values is done so there are suitable default values in the event those parameters aren't passed. As I mentioned earlier though, it's best to keep the specifics in the client code and allow users to override the settings when they create the object.

So what's going on in our object so far? Well, we're passing it the ID of the HTML element ('box') and the initial width and height. You probably noticed the dummy values of 0 for the width and height. Perhaps you're asking yourself why not simply do something similar to the following:

1. function BoxObj(domId, width, height){

Page 17: Présentation de JSON

2.     this.domId = domId;3.     this.width = width;4.     this.height = height;5.     ...6.     ...

7. }

Doing so is normally frowned upon because there is no way to monitor what is getting configured into the object -- no way to validate the parameters. A better approach is to run a bootstrap function whenever the object is instantiated whose sole purpose is doing the setup work to ensure the object is configured correctly. This method is commonly called init().

In our Box Class, we're going to have init() make sure that the width and height parameters are strictly integers (in case someone passes a funky value).

Creating the Class - Methods

Alright, so let's just dive right in and take a look at a method.

1. function BoxObj(domId, width, height){2.  3.     this.domId = '';4.     this.width = 0;5.     this.height = 0;6.     this.color = "red";7.  

8.     this.init = function(){9.         this.domId = domId;10.         var elm = document.getElementById(this.domId);11.         this.width = elm.style.width = parseInt(width) + 'px';12.         this.height = elm.style.height = parseInt(height) + 'px';13.         elm.style.backgroundColor = this.color;14.         elm.style.display = 'block';15.     }16.  

Page 18: Présentation de JSON

17.     // init() runs when the object is instantiated18.     this.init();19. }

As you can see, creating a method is done similarly to adding an attribute. Before you said "this.something" equals a string, or "this.something" equals an integer and now you're saying "this.something" equals a function -- an anonymous function to be precise. In particular you are saying "this.init = function(){}", or "this object now has a method called init()".

Here's what init() did in order:

o set the object attribute of domId to whatever was passed into the parameter "domId"

o set the object attribute of width to whatever was passed into the parameter "width" set the width of the

HTML element with the ID of what ever this.domId now equals.

o set the object attribute of height to whatever was passed into the parameter "height" and set the height

of the HTML element with the ID of what ever this.domId now equals.

o set the background color of the HTML element with the ID of what ever this.domId now equals to "red" (i

wanted to leave one non-overridden attribute to show you it works).

The very last line of the class calls the init() function, so when you instantiate the object it will automatically setup the attributes with the parameters you passed in.

1. box = new BoxObj('box', '100px', 100);2. // notice I passed in '100px' but it returns 100 -- init() at work3. // box.width and box.height are 1004. // box.color would be "red"

Here are the rest of the methods: makeBigger(), makeSmaller(), and changeColor().

1. function BoxObj(domId, width, height){2.  3.     this.domId = '';4.     this.width = 0;5.     this.height = 0;6.     this.color = "red";7.  

8.     this.init = function(){9.         this.domId = domId;10.         var elm = document.getElementById(this.domId);11.         this.width = elm.style.width = parseInt(width) + 'px';12.         this.height = elm.style.height = parseInt(height) + 'px';13.         elm.style.backgroundColor = this.color;14.         elm.style.display = 'block';15.     }16.     this.makeBigger = function(){17.         var elm = document.getElementById(this.domId);18.         this.width = elm.style.width = (parseInt(this.width) * 2) + 'px';19.         this.height = elm.style.height = (parseInt(this.height) * 2) + 'px';20.     }21.     this.makeSmaller = function(){22.         var elm = document.getElementById(this.domId);23.         this.width = elm.style.width = (parseInt(this.width) / 2) + 'px';

Page 19: Présentation de JSON

24.         this.height = elm.style.height = (parseInt(this.height) / 2) + 'px';25.     }26.     this.changeColor = function (color){27.      

this.color = document.getElementById(this.domId).style.backgroundColor = color;28.     }29.  

30.     this.init();31. }

Now there is no real secret to what these methods do. The thing to note is the way we are relying on using the attributes of the object to work with the attributes of the HTML element it represents. For example, makeBigger() takes the width property of the object, this.width, multiplies it by two and reassigns its value to this.width. The same is true for the height.

We never once asked the HTML element what its width or height was, we just asked the object that represents it. That's the beauty of using objects -- it's faster, easier to manage and you can reuse the code.

Download the Demo

Included in this article is an HTML file that shows you how to implement this class with client code. In a working scenario, the class would be in a separate (external) JavaScript file -- perhaps mylibrary.js. You can download the file from the attachment link below.

Error handling was left out of this class and the other functions not shown in this article for the sake of simplicity. In the real world, for example, the chageColor() method would have type-checking to ensure that the color parameter passed was valid and if not change to a suitable default, or perhaps do nothing at all.

http://www.itnewb.com/tutorial/Beginners-Guide-to-JavaScript-Objects-Methods-and-Attributes

Page 20: Présentation de JSON

Guide to JavaScript Timers with setTimeout() and setInterval()By Andrew Johnson May 8, 2009

JavaScript timers allow us to add the dimension of time to our scripts. You can use the setTimeout method to execute code once, when a specified period of time passes, or setInterval if you wish to create a loop where the code runs over and over at the interval you specify.

JavaScript TimersJavaScript timers allow us to add the dimension of time to our scripts. You can use thesetTimeout method to execute code once, when a specified period of time has passed, or the setInterval method can be used to create a loop where the code runs over and over at the interval you specify.

There is also the clearTimeout and clearInterval methods which are used to clear or "cancel" a setTimeout or setInterval operation. For example, you might setup a setInterval operation and then use a setTimeout call that executes clearInterval after a specified period of time to cancel the interval operation.

setTimeout

setTimeout( expression, int milliseconds )

setTimeout and setInterval both take two parameters: 1) the expression/code you want to run; and 2) the number of milliseconds to wait before running the code. You can pretty much do whatever you want in the expression and, as you might expect, pass an integer variable as the milliseconds parameter which creates the possibility for code that dynamically computes the duration to use based on test cases.

Here is a very basic setTimeout() example. From the moment this line runs, a timer starts and then "times out" after 2,000 milliseconds (2 seconds) and runs the code -- in this case, the expression or code to run is a simple alert() that says "Hello World!".

1. setTimeout("alert('Hello World!')", 2000);

Here is another example that uses a variable in the alert(). The resulting alert output will say "Can you say foobar?".

1. var saywhat = 'foobar';2. setTimeout("alert('Can you say "+saywhat+"?')", 2000);

As mentioned above, you can do whatever you like in the expression area. In this next example I setup a user-definedfunction called helloWorld, which accepts a string as its only parameter. The string passed is then used in the alert call.

Page 21: Présentation de JSON

1. function helloWorld(strParam) {2.     alert(strParam);3. }4.  

5. setTimeout("helloWorld('Hello, world!')", 2000);

Here we have the same thing but I'm passing a variable.

1. function helloWorld(strParam) {2.     alert(strParam);3. }4.  5. var saywhat = 'Hello, world!';6. setTimeout("helloWorld('"+saywhat+"')", 2000);

Again, you can do whatever you want in the expression area. So, if you want to call 2 functions or modify the values of other variables you can. In the following example the sayagain variable is initially set to "foobar", but is changed to "Hello, again!" in the expression area right before the helloAgain() function is called.

1. function helloWorld(strParam) {2.     alert(strParam);3. }4. function helloAgain(strParam) {5.     alert(strParam);6. }7.  8. var saywhat = 'Hello, world!';9. var sayagain = 'foobar';10. setTimeout(11.     "helloWorld('"+saywhat+"');" +12.     "sayagain = 'Hello, again!';" +13.     "helloAgain(sayagain)",14. 2000);

You can also use anonymous functions as this next example demonstrates.

1. function helloWorld(strParam) {2.     alert(strParam);3. }4. function helloAgain(strParam) {5.     alert(strParam);6. }7.  8. var saywhat = 'Hello, world!';9. var sayagain = 'foobar';10. setTimeout(function() {11.     helloWorld(saywhat);12.     sayagain = 'Hello, again!';13.     helloAgain(sayagain);14. }, 2000);

Page 22: Présentation de JSON

clearTimeout

clearTimeout( timeoutVariable )

Up to this point, we haven't assigned the timers into variables. As you can see above, clearTimeout expects such a variable. Consider the following example, which creates a timer and then immediately clears it (the alert will never execute).

1. // Create timer, assign to variable2. var timer = setTimeout("alert('Hello World!')", 2000);3.  4. // Clear the timer5. clearTimeout(timer);

setInterval

setInterval( expression, int miliseconds )

setInterval works just like setTimeout except that it creates a loop, executing the code over and over at the specified time interval. Often, I find myself using a combination of these set and clear methods to produce the exact behavior I'm in need of.

The following example alerts "Hello, world!" every 2 seconds in an infinite loop. Remember, a setInterval operation will not stop executing until you stop it from doing so with clearInterval.

1. setInterval("alert('Hello, world!')", 2000);

clearInterval

clearInterval( intervalVariable )

clearInterval works just as clearTimeout above. Here, I setup an interval and then use the setTimeout method that executes clearInterval after 9.5 seconds, terminating the interval operation.

1. // Alert Hello, world! every 2 seconds2. var interval = setInterval("alert('Hello, world!')", 2000);3.  4. // At 9.5 seconds, clear the interval5. setTimeout(function(){6.     clearInterval(interval);7. }, 9500);

That's it, pretty easy huh?

Page 23: Présentation de JSON

Beginners Guide to AJAX (Asynchronous JavaScript and XML)By Andrew Johnson Dec 29, 2008

Asynchronous JavaScript and XML allows you to communicate with server-side scripts behind the scenes via a JavaScript XMLHttpRequest object. In this article you'll learn all about AJAX, the XMLHttpRequest class and how to start developing interactive web pages with AJAX. A basic knowledge of HTML, CSS and JavaScript is assumed.

IntroductionIn the past web pages were limited in the sense they had to load in their entirety. Changing even a small portion of the content required a new web page to be loaded.

Thankfully modern web sites don't suffer from this restriction because AJAX allows us to communicate with server-side scripts behind the scenes via a JavaScript XMLHttpRequestobject after a web page has loaded.

When you vote on an ITNewb article AJAX is used to send the request to one of our servers which updates the database and responds with a simple XML document that contains updated statistics. The response is then used to update a few areas on the web page with the new voting statistics without the web page itself ever reloading.

An XMLHttpRequest object isn't limited to the HTTP protocol as its name implies but also supports other connection types such as FTP. You can send and receive information in XML, HTML or plain text via GET, POST, HEAD or any other method supported by your server. This really opens things up and allows us to take interactive web applications to the nth level.

Prerequisites

This article assumes you have a basic knowledge of HTML, CSS and JavaScript. If you don't you may find this article hard to follow, especially on the JavaScript front. In the event you're not quite ready for this article, here are a few links to help get you started.

o Web Development Articles

o HTML Articles

o CSS Articles

o JavaScript Articles

Where it Started

The class needed to make HTTP requests with JavaScript was first introduced in Internet Explorer 5 as an ActiveX object called XMLHTTP. Mozilla (1.0 / Netscape 7) and Safari (1.2) followed suite by implementing

Page 24: Présentation de JSON

the XMLHttpRequestclass into their browsers which supported the properties of the original Microsoft ActiveX object.

For some time these nifty JavaScript classes were little known but their popularity grew as high profile sites like Google began using them.

How it works

When you think of AJAX you shouldn't think of JavaScript by itself. AJAX works through a combination of various technologies all coming together to produce powerful results. The AJAX equation involves incorporating the following technologies:

o HTML / XHTML and CSS for presentation

o Client-server communication via an XMLHttpRequest object

o Crawling the DOM and modify DHTML via a client-side scripting language like JavaScript

JavaScript events are usually used to trigger AJAX, such as a user clicking a hyperlink or perhaps a timer expiring. Here is how the entire process works from start to finish.

o An event occurs that calls a JavaScript function;

o the JavaScript function creates or reuses a request object;

o a callback function is assigned to handle the server response;

o the request is formulated and sent via the request object;

o the server processes the request and responds;

o the callback function catches the response, parses it and updates the DHTML; and

o finally the updated presentation is shown to the user.

Continue with XMLHttpRequest Class ➜

XMLHttpRequest ClassNow that you have a basic idea of how AJAX works let's delve into the XMLHttpRequest class. Once we've explored the basics and looked at a few code examples we'll get a little deeper on the next page and finish by building a real-world working example.

Page 25: Présentation de JSON

Creating a Request Object

Sending an HTTP request with JavaScript revolves around the XMLHttpRequest class. The process of instantiating the class differs on the major browsers so a few checks are required to ensure the object is successfully created. Here is how we can create a basic cross-browser request object.

1. var httpRequest;2. if ( window.XMLHttpRequest ) { // mozilla, safari, opera, chrome, ie73.     httpRequest = new XMLHttpRequest();4. } else if ( window.ActiveXObject ) { // ie, avant, aol explorer5.     try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP") } // ie66.     catch (e) {7.         try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP") } // ie58.         catch(e) { }9.     }10. }

A simple if else if control structure is used to determine the type of browser we're dealing with. The else if is entered when an old IE or similar browser is being used and inside you'll find try catch statements, which are one means of catching errors in JavaScript.

1. try {2.     // try this code3. } catch (error) {4.     // do this if an error occurred5. }

The first try catch checks to see if Msxml2.XMLHTTP is available and if an error occurs tries Microsoft.XMLHTTP which is needed to support IE v5.

Methods & Attributes

Now that we have a basic request object to work with let's take a look at some of the methods and attributes available in the object. Be sure that you always use these methods and attributes in the order presented, otherwise you'll likely run into some trouble.

open(string mode, string url [, boolean asynchronous [, string user [, string password]]]) method

o mode:  request type such as GET, POST or HEAD

o url:  location of the file or script

o asynchronous:  optional; true (yes) or false (no); defaults true

o user:  optional; for authentication; defaults empty string

o password:  optional; for authentication; defaults empty string

1. // start preparing for a request2. httpRequest.open('GET', '/ajax.php?arg1=value', true);

Page 26: Présentation de JSON

When you formulate the URL for a GET request do so just as you normally would. If you're passing arguments to a script append ?arg1=value2&arg2=value2 and so on. When POSTing, you'll want to pass the query string to the send()method detailed below but do not include the question mark at the beginning of the query string.

setRequestHeader(string header, string value) method

o header:  HTTP header (Content-Type, Content-Length etc)

o value:  value of the header

1. // set request headers, if any2. // this particular header is needed when POSTing a form3. httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

onreadystatechange attribute

The onreadystatechange attribute is used to assign a callback method that will handle the server response. Be sure you always call this after open and before send.

1. // notice only a reference to the callback is assigned2. httpRequest.onreadystatechange = theCallbackFunction;3.  4. // the callback method5. function theCallbackFunction() {6.     // wait for a response and then do something with it7. }

send([mixed requestData]) method

o requestData:  optional; empty for GET; HTTP request body for POST

1. // send request to the server2.  3. // GET example4. httpRequest.send();5.  6. // POST example7. var value1 = 'some value';8. var value2 = 'some value';9. var requestData = 'arg1=' + value1 + '&arg2=' + value2;10. httpRequest.send(requestData);

Request data from forms will usually need to be escaped or URL encoded so it doesn't interfere with your JavaScript code. I prefer to use the encodeURIComponent function on user supplied request data and other affected request data to ready it.

Page 27: Présentation de JSON

1. var requestData = 'arg1=' + encodeURIComponent(value1) +2.     '&arg2=' + encodeURIComponent(value2);

readyState attribute

The ready state code changes from 0 to 4 during the request cycle and needs to be checked in your callback function so it knows when the response has arrived.

o 0: Request not initialized

o 1: Connection established (ready for setRequestHeaders and send)

o 2: Response headers received

o 3: Receiving response body

o 4: Complete (response ready)

1. function theCallbackFunction() {2.     if ( httpRequest.readyState == 4 ) { // request complete3.         // continue processing4.     }5. }

status attribute

This status attribute stores the HTTP response code. The response code 200 means OK, 404 means Document Not Found and so on. Read section 10 (Status Code Definitions) of the HTTP/1.1 specification for a complete list of possible response codes.

1. function theCallbackFunction() {2.     if ( httpRequest.readyState == 4 ) { // request complete3.         if ( httpRequest.status == 200 ) { // request successful4.             // extract the response text or xml5.             // and do something with it6.         }7.     }8. }

responseText attribute

Once you've successfully received a response from the server you can use either the responseText or responseXMLattributes to extract it, depending on the response type of course. For text / html responses use responseText and if it's an XML response you'd use responseXML.

1. function theCallbackFunction() {2.     if ( httpRequest.readyState == 4 ) { // request complete3.         if ( httpRequest.status == 200 ) { // request successful4.             alert(httpRequest.responseText);5.         }6.     }7. }

responseXML attribute

Page 28: Présentation de JSON

When working with XML responses you MUST make sure the server sends the Content-Type: text/xml response header, otherwise you'll run into trouble when trying to access it. You also need to ensure a valid XML document is returned such as the following example that includes some bogus company information.

1. <?xml version="1.0" ?>2. <root>3.     <company>Menlo Perkins, LLC</company>4.     <address>3817 Mendelson Ave.</address>5.     <phone>111-222-3333</phone>6. </root>

You can target elements by tag with the getElementsByTagName method and use the childNodes and nodeValueproperties to move around and access values.

1. var xmlDoc = httpRequest.responseXML;2. var company = xmlDoc.getElementsByTagName('company')[0].childNodes[0].nodeValue;3. var address = xmlDoc.getElementsByTagName('address')[0].childNodes[0].nodeValue;4. var phone = xmlDoc.getElementsByTagName('phone')[0].childNodes[0].nodeValue;

Completed callback example:

1. function theCallbackFunction() {2.     if ( httpRequest.readyState == 4 ) { // request complete3.         if ( httpRequest.status == 200 ) { // request successful4.             var xmlDoc = httpRequest.responseXML; // extract the response5.             if ( xmlDoc == '' or xmlDoc == null ) { // invalid XML?6.                 alert("Invalid XML Document Received");7.                 return false;8.             }9.             var company = xmlDoc.getElementsByTagName('company')

[0].childNodes[0].nodeValue;10.             var address = xmlDoc.getElementsByTagName('address')

[0].childNodes[0].nodeValue;11.             var phone = xmlDoc.getElementsByTagName('phone')

[0].childNodes[0].nodeValue;12.             alert("Company: " + company + "\n\nAddress: " + address + "\n\nPhone:

" + phone);13.         }14.     }15. }

Cached AJAX Responses

The same caching issues that apply to typical HTTP requests also apply to HTTP requests made with AJAX. If your server-side scripts don't include HTTP headers to prevent responses from being cached they will be. Depending on what you're fetching you may want the response to be cached but more often than not you probably won't.

To prevent AJAX responses from being cached have your web server or server-side scripts include the Cache-Control and Pragma response headers. Here is how you can do it in PHP scripts:

Page 29: Présentation de JSON

1. <?php2.  3. $response = "Don't cache me!";4.  5. header("Content-Type: text/html");6. header("Cache-Control: no-cache");7. header("Pragma: no-cache");8.  9. echo $response;10.  

11. ?>

DHTML / Working with the DOM

DHTML (Dynamic Hypertext Markup Language) is a term used to describe web pages which use a combination of markup (XHTML), client-side scripting (JavaScript), a presentation language (CSS) and the DOM to create interactive properties.

The Document Object Model is an API for valid HTML / XHTML and well-formed XML documents. It is a platform and language independent object model for representing these formats that allows programmers generic access to the elements, objects, attributes and properties associated with them. In a nutshell, the DOM allows us to access, crawl and dynamically modify elements through browser supported languages like JavaScript, Java and VBScript.

For those of you who are new to these technologies I wanted to briefly describe them and talk about a few of the basics which are relevant to the code we'll be looking at on the next page. If you're already familiar with DHTML you can safelyjump ahead.

Targeting Elements

The easiest way to target a DOM element is by assigning it a unique id in your markup. Here we have a primary <div> container from an XHTML document with a few nested divs inside it. When assigning "id"s to your elements try to be descriptive.

1. <div id="container" class="container">2.     <div id="head" class="head">3.         <!-- logo, navigation etc -->4.     </div>5.     <div id="content" class="content">6.         <!-- body columns and content -->7.     </div>8.     <div class="foot">9.         <!-- web page footer, links etc -->10.     </div>11. </div>

The JavaScript document object is the parent of the various child elements, objects and attributes within a web page. Tags within a web page are elements or objects which have attributes associated with them. For example, class and idare attributes of the primary <div> container and can have attributes all their own (for example, the class may have CSS attributes associated with it like text-align, font-size and so on).

The document object has a method called getElementById which can be used to target the DOM element with the specified id. For example, you could target the primary <div> container as follows:

Page 30: Présentation de JSON

1. var container = document.getElementById('container');

Basic Operations

Now the container variable points to the container <div> and allows for easy access to it. Here are a few very basic examples of how one might modify the container element.

1. // apply or change the containers CSS class2. container.className = "someNewClass";3.  4. // completely hide the container5. // changes CSS property of the display attribute to none6. container.style.display = 'none';7.  8. // show the container again9. // changes CSS property of the display attribute to block10. container.style.display = 'block';11.  12. // put the contents of the container into a variable13. var containerContents = container.innerHTML;14.  15. // change the contents of the container16. container.innerHTML = "I'm the new contents!";

Continue with Delving Deeper ➜

Delving DeeperAt this point you should have a decent understanding of how AJAX works, be familiar with the methods and attributes of the XMLHttpRequest class that were covered as well as a basic understanding of the DOM.

Synchronous vs. Asynchronous

As you'll probably recal the XMLHttpRequest open method can accept a boolean parameter indicating whether anasynchronous request should be used.

Synchronous

When synchronous requests are used scripts will stop and wait for a response from the server before they continue. In other words, the web page will effectively become frozen. This also means you won't be able to send simultaneous requests (2 or more requests at the same time).

There are times when this functionality may be desired which is why it exists but more often than not this is probably not what you want.

Asynchronous

Asynchronous requests will give control back to the browser while they wait for responses, which means users can continue interacting with the web page. When the request completes the callback function catches the response and updates the web page with the new information. Using asynchronous requests also means you can send simultaneous requests.

Page 31: Présentation de JSON

httpRequest Scope; Race Conditions

On the previous page the httpRequest object was created globally which is why it was available in the callback function even though we never passed it. If you use a global request object race conditions are possible unless you use a global requestObjectBusy variable to prevent them.

A race condition occurs when two or more competing processes cause the output and/or result to be altered in an unintended way. In the context of the httpRequest object, a race condition could occur if an AJAX request was made before a previous request finished thereby overwriting the httpRequest object and interrupting the first request.

An obvious solution would be to use a unique request object for every request.

sendRequest()

It is always a good idea to try and reduce redundancy in our code. The following sendRequest function aims to do just this. While it may appear a bit heavy at first, in the long run it will greatly reduce the size of your code if your site uses a lot of AJAX. This function can handle most request types and its shortcomings could be easily overcome with a few minor modifications.

sendRequest(string mode, string url, string args, boolean async, function callback, mixed cArgs, string respType, inttimeout)

o mode:  request type; used with the open() method

o url:  address of the file or script

o args:  query string to append to url or use in the send() method, if any

o async:  whether to use asynchronous; used in the open() method

o callback:  callback method

o cArgs:  arguments to pass to callback; null if there are none

o respType:  type of response; text or xml

o timeout:  number of seconds until the request should timeout

1. function sendRequest(mode, url, args, async, callback, cArgs, respType, timeout) {2.  3.     // create object4.     var httpRequest = false;5.     if ( window.XMLHttpRequest ) { // mozilla, safari, opera, chrome, ie76.         httpRequest = new XMLHttpRequest();7.     } else if ( window.ActiveXObject ) { // ie, avant, aol explorer8.         try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP") } // ie69.         catch (e) {10.             try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP") } // ie511.             catch(e) {12.                 httpRequest = false;13.             }14.         }15.     }16.  17.     // object creation fail?

Page 32: Présentation de JSON

18.     if ( ! httpRequest ) {19.         alert("Error: unable to create httpRequest object");20.         return false;21.     }22.  23.     // if GET with arguments append query string to url24.     if ( mode == 'GET' && args.length ) url += '?' + args;25.  26.     // establish connection27.     httpRequest.open(mode, url, async);28.  29.     // boolean timedOut; start out true30.     // the response handler sets to false on success31.     var timedOut = true;32.  33.     // create a timer to check the value of timedOut in (timeout) seconds;34.     // if timedOut is true, abort the request and clean up35.     setTimeout( function() {36.  37.         // timedOut true?38.         if (timedOut) {39.             httpRequest.abort(); // abort request40.             alert("Error: ajax request timed out");41.         }42.  43.         // nullify httpRequest44.         httpRequest = null;45.  46.     }, timeout * 1000 );47.  48.     // if POST, set necessary request headers49.     if ( mode == 'POST' ) {50.         httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-

urlencoded');51.         httpRequest.setRequestHeader('Content-Length', args.length);52.     }53.  54.     // assign callback method via anonymous function55.     httpRequest.onreadystatechange = function() {56.         try {57.             // response ready?58.             if ( httpRequest.readyState == 4 ) {59.                 // request successful?60.                 if ( httpRequest.status == 200 ) {61.  62.                     // set timedOut to false63.                     timedOut = false;64.  65.                     // set response66.                     var response = respType == 'text' ?67.                         httpRequest.responseText :68.                         httpRequest.responseXML;69.  70.                     // pass to callback method71.                     cArgs != null ?72.                         callback(response, cArgs) :73.                         callback(response);74.                 }75.             }76.         } catch(e) { alert("Error: communication exception"); }77.     };78.  79.     // send request80.     httpRequest.send(args);81. }

Page 33: Présentation de JSON

Now let's walk through the sendRequest function and see what all it does. The first thing you notice is that it always creates a new httpRequest object, which means you never have to worry about race conditions pertaining to the object. It also means simultaneous requests are safely supported.

On line 24 the args parameter is appended to the url if the request type is GET, so before calling sendRequest you just need to prepare the query string. Bare in mind that if you want to pass an argument to your server-side script you'll need to prepare a query string whether the request type is GET or POST. Line 24 simply prepends a question mark to the query string and appends the query string to the url if it's dealing with a GET request. For post, the args parameter is simply used in the send() method as explained earlier in this article.

1. // constructing GET-POST query string2. var args = 'arg1=' + value1 + '&arg2=' + value2;3.  4. // when there are no args to pass5. var args = '';

Line 27 opens a connection to the server and line 31 adds a timedOut variable which defaults true. On line 35 a timer is created which contains an anonymous function that will check the value of timedOut in (timeout) seconds. The response handler which starts on line 55 will set timedOut to false as soon as it receives a valid response from the server.

In the event the response handler wasn't able to set timedOut to false because the readyState never reached 4 or a 200 HTTP response code wasn't sent lines 38 through 44 will a) abort the request and b) nullify the httpRequest object.

When sendRequest is dealing with a POST request it will set the Content-Type and Content-Length HTTP request headers. These headers must be present when POSTing to your server-side scripts.

Alright, now let's take a look at lines 55 through 75 -- assignment of the callback method. Assigningonreadystatechange an anonymous function is advantageous because it allows us to do whatever we want inside the function such as the ability to pass our callback method arguments. In this code the anonymous function checks the readyState and status attributes and when the response is ready passes it off to the callback method specified in the sendRequest callback parameter.

1. // calling sendRequest2. sendRequest(.., .., .., .., theCallback, .., .., ..);3.  4. // the callback method5. function theCallback(response) {6.     // do some stuff7. }

More often than not you'll probably want to pass callback methods more than simply the response. For example, you may want to pass it the id of the DOM element you'll be modifying as its id may be dynamically generated by your scripts.

This is where the cArgs parameter comes into play. If you want to pass more than one argument construct cArgs as an object where the attributes are your arguments. If your callback method only takes the response send null as the cArgs value.

1. // when the callback method takes 1 additional argument

Page 34: Présentation de JSON

2. sendRequest(.., .., .., .., theCallback, theArgument, .., ..);3.  4. // the callback method5. function theCallback(response, theArg) {6.     alert(response + ' ' + theArg);7. }8.  9. // when the callback method takes more than 1 additional arguments10. var cArgs = {11.     arg1 : 'value1',12.     arg2 : 'value2'13. };14. sendRequest(.., .., .., .., theCallback, cArgs, .., ..);15.  16. // the callback method17. function theCallback(response, cArgs) {18.     alert(response + ' ' + cArgs.arg1 + ' ' + cArgs.arg2);19. }20.  21. // when the callback only takes the response22. sendRequest(.., .., .., .., theCallback, null, .., ..);23.  24. // the callback method25. function theCallback(response) {26.     alert(response);27. }

Examples

I've put together a few examples that demonstrate sendRequest in action. The sendRequest function and the examples were tested on Firefox 2 / 3.0.4, Opera 9.27, Google Chrome 0.3.154.9, Internet Explorer 6 / 7, Safari Win32 3.03, Avant 11.5 and AOL Exporer 1.5.

The example includes the HTML, CSS, JavaScript and a PHP script. Four examples are demonstrated including Text, XML, POST and a Timeout. To get started download the attachment from the link below, extract the zip and upload/move the ajax folder to your web server and then open http://yourserver/ajax/index.html in your web browser.

Enjoy!

http://www.itnewb.com/tutorial/Beginners-Guide-to-AJAX-Asynchronous-JavaScript-and-XML