Development of Ajax Web Widget
by Roshan Bhattarai | February 2009 | AJAX
This is a 5 part mini series by Roshan Bhattarai, covering basics of Widget, development of Wiki seek Widget, Pop-up Image Widget, RSS Web Widget, and Delicious Tagometer Widget.
The web is becoming more flexible and dynamic from day to day. The service and functionality provided by a particular website is not limited to itself. We can extend it to other websites by placing a few lines of code in their web pages called Widget.
In this article we will explore the technologies that go behind making a Widget and understand its working.
We’ve seen this kind of thing done by the popular bookmark sharing website, digg.com. We don’t need to visit digg.com to digg the URL. We can do it using a small object called Widget, provided by digg.com. This is just one simple example of providing remote functionality; you can find lots of widgets providing different functionality across various websites.
What is a web widget?
A web widget is a small piece of code provided by a third party website, which can be installed and executed in any kind of web page which is created using HTML (or XHTML). The common technologies used in web widgets are JavaScript, Ajax and Adobe flash but in some places other technologies such as HTML combined with CSS, and Java Applets are also used. A web widget can be used for:
- Serving useful information from a website.
- Providing some functionality (like: voting, polling).
- Endorsing the products and services of a website.
Web widgets are also known as badges, modules, and snippets. And, these are commonly used by bloggers, social network users and advertisers.
Popular Web Widgets
You can find many examples of the web widgets on the World Wide Web. These include:
- Google Adsense – It is probably the most popular web widget you can see on the World Wide Web. All you’ve to do, is get a few lines of code from Google and place it in your website. Different kinds of contextual advertisements get displayed on your website according to the content displayed on your website.
- Digg this widget – If You want to display news or articles then you’re most probably going to do so with this widget. Provided by the social book marking website digg.com, it is one of the popular bookmark sharing websites. Your website will lots of visitors if your article gets more and more digs, and gets featured on the first page.
- Del.icio.us widget – You might have seen the widget previously, or text showing “Save to del.icio.us”, “Add to del.icio.us” and “saved by XXX users”. This is another popular social bookmarking website.
- Snap preview –Provided by snap.com, this widget shows the thumbnail preview of a web page.
- Survey widget from Polldaddy.com – If you need to run some kind of poll then you can use this widget to create and manage the poll on your website.
- Google Maps – A rather well known widget, which adds different map functionality in Google maps. you must get an api key from Google to use this widget.
Benefits of Providing Web Widgets
I came to know about dzone.com, a social bookmarking website for web and software developers, from a widget I found in a blog. Let’s look at the benefits of web widgets:
- A widget can be an excellent publicity tool. Most of the people who come to know about digg.com,del.icio.us or reddit.com do so from their web widgets in various news portal and blogs.
- Providing web services- This is useful since the user doesn’t have to visit that particular website to get its services. For example, a visitor to a website which has a Polldaddy web widgets can participate on a survey without visiting to polldaddy.com.
- Web widgets can be one of the ways of bringing income for your website, by utilizing advertising widgets such as Google adsense (discussed above).
- Widgets can generate more traffic to your website. For example, you can make a widget that evaluates the price of a product on a website. Widgets across multiple websites means visitors from multiple sources, hence more traffic to you website.
How do Web Widgets work
As can be seen in the above figure, the web widget is used by a widget client, which is a web page. The web pages just use a chunk of code provided by the functionality providing website. Furthermore, all the services and functionality are provided by the code residing on the remote server which the widget client doesn’t have to care about. In a web widget system, there is optional system called Widget Management System which can manage the output of the widget.
Widget Management System
A Widget Management System is used for controlling the various operations of the widget, including things like height or width or color. Most widget providing websites allows you to customize the way widget looks in blogs or website. For example, you can customize the size and color of Google adsense by logging into the Google adsense account system.
Some widget Management Systems also allow you to manage the content of the widget as well. In the survey widget from vizu.com, you can manage parameters like the topic of poll and number of answers of the poll.
Concept of Technologies Used
To make the most out of Ajax web widgets, let’s get familiar with some technologies.
HTML and XHTML
Hypertext Markup language(HTML) is one of the most known markup language for constructing web pages. As the name implies, we use it to markup the text document so that web browsers know how to display them.
XHTML on the other hand, is the way to standardize the HTML by making HTML a dialect of XML. XHTML comes in different flavors like transitional, strict or frameset, with each flavor offering either different capabilities or different degrees of conformance to the XML standard.
Difference between HTML and XHTML
The single biggest difference between HTML and XHTML is that XHML must be well-formed according to XML conventions. Because an XHTML document is essentially XML in nature, simply following the traditional HTML practices is not enough. An XHML document must be well formed. For example, let’s take the examples of “img” and “input” elements of HTML.
<img src="logo.gif" alt="My Site" border="0" > <input type="text" name="only_html" id="user_name" value="Not XHTML" >
Both of the above statements are perfect HTML statements but they are not well graded constructions in XHTML as they are not well formed according to compliance of XML (those tags are not enclosed properly). To figure out the difference, first look at the above tags in the XHML valid syntax.
<img src="logo.gif" alt="My Site" border="0" /> <input type="text" name="only_html" id="user_name" value="Not XHTML" />
Did you find the difference? The latter tags are well formed and the previous one is not. If you look closely, you can find that the HTML tags in the second example are closed like XML. The point is you should have well formed document in order to allow JavaScript to access the DOM.
You can also add comments in the HTML document. Any information beginning with the character string <!-- and ending with the string --> will be ignored:
<!-- This is a comment within HTML-->
You can add the comment in the same fashion in an XML document as well.
Concept of IFRAME
IFrame (Inline Frame ) is a useful HTML element for creating web widgets. Using IFrame, we can embed the HTML document from the remote server into our document. This feature is most commonly used in the web widgets.
We can define the width and height of IFrame using the height and width property of the IFrame element. IFrame can be defined in any part of the web pages. IFrame behaves like an inline object and the user can scroll through the Iframe to view the content which is out of view. We can also remove the scroll bar from the IFrame by setting scrolling property to no.
The embedded document can be reloaded asynchronously using IFrame and can be an alternative option to an XMLHttpRequest object. For this reason, IFrames are widely used by Ajax applications.
You can use the IFrame in the HTML document in the following way:
<html> <body> <iframe src="http://wwww.example.com" width="200"> If your browser doesn’t support IFrame, this text will be displayed in the browser </iframe> </body> </html>
CSS(Cascading Style Sheet)
A Cascading Style Sheet is a style sheet language which is used to define the presentation of document written in HTML or XHTML pages. CSS is mainly used for defining the layout, colors and fonts of the elements of a web page along with other perspectives of the document. While the mark up language can be used to define the content of the web page, the primary goal of providing a CSS is to separate the document’s content from the document’s presentation. The Internet Media type “text/css” is reserved for CSS.
Using Cascading Style Sheet
CSS can be used in different ways in a web page. It can be written with the <style></style> tag of the web-page. It can be defined in the style attribute of the element. Also, CSS can be defined in a different page with extension .css that links with the web page to define the presentation.
What is the benefit of using CSS then? You can define the values for a set of attributes for all HTML elements (of a similar type), then change the presentation with one change in the CSS property
<style type="text/css"> all the css declaration goes here </style>
But what about defining the CSS property for different web pages? The above method can be cumbersome and you would need to replicate the same code to different web pages. To overcome such a situation, you can define all the property in a single page let’s say call it style.css and link that CSS to the web pages.
<link href="style.css" type="text/css" rel="stylesheet" />
Furthermore, you can define the styles within the elements using the style property of the HTML elements, which is commonly known as inline styles.
<p style="text-align:justify">This is content inside paragraph</p>
As you’ve seen, we’ve quickly defined the text-align attribute to justify
Defining Style Sheet rules
A style sheet allows you to change the different attributes of the HTML elements by defining a styling rule for them. A rule has two components: selectors, which defines which HTML elements to apply the styling rule and declaration, which contains the styling rule for the selectors.
p { background-color:#999999 }
In the above css rule, p is the selector and background-color:#999999, is the declaration of the rule. The above style defines the rule for the paragraph element <p></p>.
.box { width:300px }
In the above rule, selectors is defined as a class and it can be used in any element with the class property of the element.
<p class="box">..content..</p> <div class="box">content</div>
Class can be used with any HTML element.
#container { width:1000px }
“#” is known as an id selector in CSS. The above rule applies to an element which has the id “container” such as below:
<div id="container">..content..</div>
We can also define a set of rules for multiple elements using comma (,) among the selectors:
h1, h2, h3 {font-size:12px; color:#FF0000 }
There are many more styles of defining selectors and CSS properties.
JavaScript
JavaScript is a prominent client side scripting language. It evolved from a language called LiveScript, which was developed by Netscape for use in the browsers of early days. JavaScript source code can be embedded in the HTML pages or you can write the JavaScript in separate file and call it from HTML pages. Since it is a client side scripting language, it gets interpreted and executed by the web browsers.
With the help of JavaScript, you can manipulate DOM and add functionality to your web page. Here are the few examples:
- Open pop-up window and dialog boxes
- Add animation and effects to the web page elements
- Hide and display the object of web pages
- Change the way page elements are displayed
- Validation of user entered data
DOM is an acronym for “Document Object Model”. DOM is the hierarchical representation of the elements of XML and HTML data.
JavaScript can be disabled in web browsers. If JavaScript is not working in your browser then you check your browser settings.
Basics of JavaScript
JavaScript code can be embedded directly in the HTML pages within <script> </script> tags. As mentioned above, another way of using JavaScript code could be placing the code in the separate file with.js extension and linking them to the HTML pages where required.
<script language="javascript" type="text/javascript" scr="js_functions.js"></script>
Placing the JavaScript in the separate file allows you to use them in multiple web pages by just linking them. Furthermore, it also makes code easier to maintain and use. Now, let’s look in detail the attributes defined in the above JavaScript tag.
language=”javascript” : this is self explanatory and tells the browser that statement within the script tags should be interpreted as the JavaScript language.
type=”text/javascript” : this Internet media type declares that the script enclosed within the script tag is JavaScript.
There is an element called noscript which gets executed if the browser doesn’t support JavaScript. You can use the noscript to warn or inform the user that JavaScript is disabled in the browser, <noscript>JavaScript must be enabled.</noscript>.
Writing on HTML pages with JavaScript
As I’ve mentioned earlier, you can access the HTML pages with the help of DOM. To write something in HTML pages, you can use two functions: write() and writeln() functions of the document object. Now, let’s look at the HTML and JavaScript Code to use them.
<p> <script language="JavaScript" type="text/javascript"> document.write ("First line using JavaScript!"); document.write ("Second line using JavaScript!"); <script> </p>
Using the document.write() statement in JavaScript, we’ve written two lines in a web page using JavaScript. Here is the output of the above statements:
First line using JavaScript!Second line using JavaScript!
As you can see clearly, both lines are displayed on the same line which we don’t want. To add the line break between two statements you can use the document.writeln() function of JavaScript. Here is the output you’ll get by replacing the document.write() function with document.writeln() function:
First line using JavaScript!
Second line using JavaScript!
Second line using JavaScript!
Changing the content of elements using JavaScript
How do you change the content of the HTML element by using JavaScript when the web page is already loaded? In this case, innterHTML property comes handy so let’s look at an example of an innerHTMLproperty that changes the content of the paragraph when the button or link is clicked by the user within the web page.
<script type="text/javascript" language=" javascript"> function changeContent() { document.getElementById('paragraph').innerHTML = "Hello! Roshan"; } </script> <p id="paragraph">Hello Friend </p> <input type='button' onclick='changeContent()' value='Change Content'/>
Let’s look at the above code clearly. When the button is clicked it calls the changeContent() function of JavaScript. In that function, the content of the paragraph with id “paragraph” is replaced by “Hello! Roshan”. Before clicking the button, the paragraph had “Hello Friend” as its content.
You can even insert HTML elements using the innerHTML property.
document.getElementById('paragraph').innerHTML = "<span style=’color:#FF0000’>"Hello! Roshan"</span>";
If you use this statement in the changeContent() function, you’ll output the content in red.
Changing the style of the element using JavaScript
We already know about defining the style element using CSS. We can also do so using JavaScript, through the style property.
document.getElementById("elementId").style.color="#FF0000"; document.getElementById("elementId ").style.backgroundColor="#CCCCCC";
As you can see, we’ve changed the color and background color of the element with id “block” using thestyle property.
You should note that you’ve to write the CSS attribute in camel case when you’re accessing it through the style property in JavaScript. For example, you have to use backgroundColorinstead of background-color and marginLeft instead of margin-left.
Now, the question arises how to change the class of the element using JavaScript. You can change the CSS class name using the className property.
document.getElementById("elementId").className="box_class";
Manipulating DOM element using JavaScript
Another thing we must learn in JavaScript when creating web widgets is DOM manipulation. Sometimes, we may have to create the script object and sometimes we may have to create division div or paragraph pdynamically using JavaScript.
Let’s create the script object and attach it to the document using JavaScript. To, create the element you have to make use of the function createElement() of document object.
Var extScript=document.createElement("script");
We’ve just created a script element. Now, we can assign some values to this script element as well.
extScript.type =’test/javascript’; extScript.language =’javascript’; extScript.src =’http://www.example.com//javascript/javascript_file.js’;
We’ve just assigned three properties to this newly created JavaScript element. Now, there is one task remaining, we need to add it to the document. To do so, use the appendChild() function of the documentobject
document.body.appendChild(extScript);
Now, the newly created script element is added to the document as a child of the body element. We can use each and every function available in javascript_file.js in the document where this script is being used.
In the similar fashion, we can attach the css style sheet to the document. Here is the code to create thelink element of the document and attach it with the current document to use the style defined in a remote place:
Var extCSS=document.createElement("link"); extCSS.setAttribute(‘type’,’test/css’); extCSS.setAttribute(‘rel’’stylesheet’); extCSS.setAttribute(’http://www.example.com/css/style.css’,’’); document.body.appendChild(extCSS);
Previously, we have assigned the values to the attribute of the element using JavaScript but here we’ve used the setAttribute() function to set the value of the property of the link element. Here is the syntax of using setAttribute() function:
element.setAttribute('attributeName','attributeValue')
Note that setting values to few attribute doesn’t work in some browsers. I can’t mention all of them but element.setAttribute(‘style’’width:200px;’); doesn’t work, for example, in Internet Explorer.
Cross-browser Support
As the term suggests, Cross-browser refers to the way of developing web applications and websites in such a way that it is supported in all web browsers. Different browsers have their own way of interpreting HTML and scripting. This can lead developers to write the same code two or more times to provide support for different browsers.
For example, to set the style of a element using JavaScript you can use the setAttribute() function as:
element.setAttribute(‘style’,"width:200px;");
The above statement works fine with Safari and Firefox but doesn’t work in Internet Explorer. To provide the same functionality in IE, we’ve to write the following statement in JavaScript:
element.style.cssText="width:200px;";
As you’ve seen, you’ve to write the two different statements for providing the same functionality across different browsers.
The applications written in this article supports the current major web browsers: Microsoft Internet Explorer, Mozilla Firefox, Safari and Opera.
XML
XML stands for eXtensible Markup Language. Since, it is (also) a markup langugage, it has many similarities to the markup style of HTML. Whereas HTML is used for defining the presentation of the web page, XML documents are used for various purposes like data storage and data exchange. In fact, in the web based application XML is used for structured data interchanges between clients and servers.
Unlike HTML which has a fixed set of elements, XML can define it’s own set of elements to represent the particular data. XML documents are structured in the tree structure. A XML document must have rootelement know as parent element. All the other related elements are connected with this parent element.
The markup elements of XML are enclosed within < and > and these elements are used to annotate the content of the file describing the information it contains. The XML element is commonly referred to as atag. Furthermore, XML tags can also contain attributes similar to HTML elements. An attribute in the XML document can be defined within the starting tag of the XML elements and value of an attribute is enclosed within either quotes or apostrophes.
Let’s look at the sample of an XML document for describing the details of books in a library:
<?xml version="1.0" encoding="UTF-8" ?> <library> <book isbn="1234"> <title>The Fellowship of the Ring</title> <author>J.R.R. Tolkien</author> </book> <book isbn="4547"> <title> Pro JavaScript Technique </title> <author>John Resig</author> </book> </library>
Notice the tags and attributes. The XML document consists of a root element named “library”. All the other tags of the XML are self descriptors where the name (such as title) refers to the title of a book and author tag contains the name of the author of the book. They are well organized in the tree order. Furthermore, you’ve also noticed that we’ve defined the “isbn” as the attribute of the element in the XML document.
In contrast to HTML, XML tag names are case-sensitive. Be careful, <book> and <Book> elements are treated differently in XML.
PHP
PHP, the reverse acronym of Hypertext Preprocessor, is a popular general purpose open-source server side scripting language, used by large number of websites. PHP is composed of commands that can be embedded within the HTML code of your pages. Unlike a client side scripting language which is interpreted by the web browsers, the server side scripting language is parsed by the web server before the page is sent to the web browser.
PHP statements are enclosed within the <?php and ?> tags. Anything between such tags is evaluated by the web server, prior to the page being served to the browser. You can have as many as <?php and ?> sets of tags in the PHP page as you like. They commonly have the .php extension.
You can change different extension pages like .html or .asp to act like a PHP page which can be done by adding the following line in the .htaccess file of the web server.
AddType application/x-httpd-php .asp .html
AddType application/x-httpd-php .asp .html
You can write the HTML code to output in the browser using PHP. Here is the simple example using theecho statement.
<html> <head> <title>Example of Using PHP</title> </head> <body> <?php echo "<strong>Hello World!</strong>"; ?> </body> </html>
The above code outputs “Hello World!” in the bold text in the browser.
Basics of PHP
Variables in PHP are used to store the data. PHP variables always start with “$” sign followed by letters, digits and underscores. Variables in PHP are case sensitive.
Since PHP is a dynamic type language, it is not necessary to define the type of variable while using it. PHP takes care of these things automatically as shown below:
$quantity = 5; $product_name = ‘Apple Ipod’;
If you look at the above example, $quantity is of Integer type and $product_name is string type. PHP takes care of it all internally.
To concatenate the string, PHP has the dot(.) operator, as shown below:
$product_name = ‘Apple Ipod’.’ 2 GB’;
Thus, we’ve added “2 GB” to the string $product_name using the dot.
Parsing XML using PHP
XML is the backbone for calling APIs (Application programming Interface) in web applications. The simplest method to parse XML using PHP is by using SimpleXML functions. You can usesimplexml_load_string() and simplexml_load_file().
Note that for using these two functions, PHP must be compiled with the SimpleXML module, which is available in PHP from version 5.0.
simplexml_load_string() is used for parsing the XML string to a SimpleXML object whereassimplexml_load_file(), as the name denotes, is used for converting the XML document into simpleXML object.
Let’s parse the XML string defined in the Library data example. We can use the following statement.
$parsedXML=simplexml_load_string($xmlString);
If the XML data is in the library.xml file then we can use simplexml_load_file() to achieve the same:
$parsedXML=simplexml_load_file(‘library.xml’);
As we have the $parsedXML variable in the form of simpleXML object, we can output the “author” node by using the following statement in PHP:
echo $parsedXML->book[1]->author;
To access the “isbn” attribute of the first “book” node, we can do it by:
echo $parsedXML->book[0]['isbn'];
To print the “title” element of each node we can use the foreach() loop of PHP:
foreach($parsedXML->book as $books) { echo $books->title."<br />"; }
The above statement outputs the following line in the web browser. Remember that we’ve used the “<br />” element to display each title in the new line.
The Fellowship of the Ring
Pro JavaScript Technique
Pro JavaScript Technique
AJAX
Ajax stands for Asynchronous JavaScript and XML. Ajax itself is not a technology; it is a mixture of well-known programming techniques that enable web developers to build Rich Internet Applications with more appealing user interfaces by providing the data transfer from the web server in asynchronous manner.
While working in the Desktop application, we get the result of the work immediately. For example, if you click the ok button of a message box then you’ll get the output of that action immediately. But, this sort of interaction is hardly available for the user of the web-based application. The common scenario is to click on a link, and then sit back until the server processes the request and sends the response to the browser. The whole page will reload – sometimes slowly.
Ajax is the solution to this kind of problem by acting as a middle layer between the web browser and server. In an Ajax application, the server request doesn’t need to be synchronized with the user action (such as clicking on a link, or clicking on a button). An Ajax application requests the data from background and the server sends the response to the web page without reloading the whole page. This is why we call Ajax “Asynchronous”.
Although XML is in the acronym of Ajax, It’s not always necessary to use XML in your Ajax application. You can use and manipulate the server request and response in ASCII and HTML formats as well.
XMLHTTPRequest Object
XMLHTTPRequest Object is the core component for AJAX, originally created by Microsoft to use in its Office Suite. Later, outside developers found the importance of the XMLHTTPRequest object. For security reasons, the XMLHTTPRequest object can generally only make calls to the server side file within the same domain as the calling page, and cannot directly call a remote server. Ajax allows server response to be transferred in different formats like ASCII text or XML data.
Regarding the request to server side scripting, the communication from server side scripting with XMLHTTPRequest is just another HTTP Request. So, you are not restricted to use a particular server side scripting language for making server calls.
XMLHTTPRequests can be used to get responses from server in both synchronous and asynchronous ways. Since, XMLHttpRequest is most commonly used for asynchronous requests and responses, we’ll not be looking towards the synchronous part in this article.
The following statement is used to create the instance of an XMLHTTPRequest named xmlHttp:
var xmlHttp = new XMLHTTPRequest();
The above statement creates an XMLHTTPRequest object in non-IE browsers (e.g. Firefox, etc). In IE, theXMLHTTPRequest object is implemented as a ActiveX Object. An ActiveX Object is a proprietary part of Microsoft technology for enabling ActiveX objects in web pages. It is only supported by Internet Explorer.
To create an object of XMLHTTPRequest in Internet Explorer we’ve to write the following statement in JavaScript:
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
But there is still a complication in IE. Some versions of Internet Explorer use different versions of MSXML parsers. In that case you’ve to use the following statement to create the same object:
var xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
Now you know that how to create object of XMLHTTPRequest object in different browsers. But there is one issue, we have to create the application in such a way that it must be applicable to all the browsers which support XMLHTTPRequest. Here is a cross-browser function which returns the object of XMLHTTPRequest from all the supported browsers:
function getXMLHttpObject() { var xmlhttp=false; try { xmlHttp=new XMLHttpRequest(); } catch(e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e1) { xmlHttp=false; } } } return xmlHttp; }
The above function uses JavaScript’s try and catch statement to handle the exception. If the statement inside the try block throws an error then the control is transferred to the catch block next to it.
Function to handle Ajax request and response
Now let’s look at an example of a function in an AJAX application which handles the server’s request and response asynchronously using XMLHTTPRequest.
function ajaxCall(somevalue) { //create the instance of the XMLHTTPReqest Object var requstObj= getXMLHttpObject(); // build the URL of the server script we wish to call var url = "server_script.php?value=" + somevalue; // XMLHTTPRequest object opening server connection requstObj.open("GET", url, true); //function to handle the response when readystate // of XMLHTTPRequest is changed. requstObj.onreadystatechange = function() { if (requstObj.readyState == 4) //when the response is completed { // only if http status is "OK" if (requstObj.status == 200) { //output the response text in alert box alert(‘The response from server is: ’+ requstObj.responseText); } else { alert(‘Error occurred :’+ requstObj.status); } } // and finally send the request to server requstObj.send(null); }
Now, let’s examine the ajaxCall() function:
var requstObj= getXMLHttpObject();
In the first line of this function, the cross-browser XMLHTTPRequest object is assigned in requstObj variable.
var url = "server_script.php?value=" + somevalue;
The above line contains the name of the server script which is going to be called from the XMLHTTPRequest object. In this case, we’re going to call PHP script with “value” as a GET parameter.
requstObj.open("GET", url, true);
In the above statement, we’re going to call the PHP script with the HTTP GET Method. The third parameter of open() method specifies whether the server script is going to be called synchronously or asynchronously. The ‘true’ value specifies that the request is going to asynchronous.
requstObj.onreadystatechange = function() { if (requstObj.readyState == 4) //when the response is completed { // only if http status is "OK" if (requstObj.status == 200) { //output the response text in alert box alert(‘The response from server is: ’+ requstObj.responseText); } else { alert(‘Error occurred :’+ requstObj.status); } } }
As you can see, an inline function is called which we generally call a response handler in the AJAX application. The above statement just defines that this response handler function is going to be called when the object’s readyState property is changed. The readyState 4 represents that the request status is completed and ready to get the response. The plaintext response from the server can be found inresponseText property of the object. The status property of object represents the HTTP status of the response. We can use the response requstObj.responseText of the above function in our application according to our need. The statement requstObj.status == 200 represents that we’re only going to process the response if we get an OK response (HTTP status code 200) from the server.
XMLHTTPRequest contains another property named responseXML to handle the response returned in the XML format by the server. We can use the getElementByTagName() DOM manipulation function to handle the XML response in JavaScript.
requstObj.send(null);
And finally, the above send function of the XMLHTTPRequest object sends the request to the server. Since, we’re using the GET method to send the request, we’ve entered null as the parameter in the send()function because we’re using the GET request and parameters are sent via the URL in the open()function. If we had used the POST request method then, we would have used the following statement to send the request to server.
requstObj.send(‘value=’ + somevalue);
When sending a request to the server using the POST method, we have to specify those variables in thesend() method of XMLHTTPRequest Object.
Web Services
In a typical web based application, a web client (usually a browser) sends an HTTP request to a web server, and the web server sends the response via an HTTP protocol to the client. For example, let’s suppose you want to get the weather report of a particular city. In this scenario, you visit a news portal and search your city’s weather report via HTML in that news portal.
But, Web Services act in a different manner. Web Services cause a server to expose application logic, which the client can use programmatically. In simple terms, it means that the server exposes a set of APIs (i.e. functions) which the client can call.
Since the API exposed using web services should be platform independent, XML is used for the communication between the client and server. The server which exposes the set of functions are usually described using a language called Web Services Description Language (WSDL).
Web services are a set of tools that can be used in a number of ways. The three most common styles of using them are REST, XML-RPC and SOAP.
While creating web widgets, we may have to use various standards of web services and let’s take a short glance at these technologies.
SOAP
SOAP stands for Simple Object Access Protocol and is by far the most popular method of remote access on the Internet. It is a protocol for exchanging XML based messages from client to server, normally using HTTP and HTTPS protocols. SOAP procedures which are exposed in the XML format can be used by a client using SOAP protocol.
SOAP is an XML based messaging-protocol. A SOAP request in XML format contains the following main parts:
- An Envelope – It defines the document as a SOAP request
- A Body Element – It contains the information about the procedure called with parameters and expected response.
- Optional headers and fault element – It contains the supplementary information about the SOAP request.
A typical example of how SOAP procedures can be used, is when a website exposes a function called addTwoNumbers() to add two numbers and send the response to the SOAP client. Since, SOAP’s request and response are sent using the XML format they are platform independent and can be called from the remote server.
SOAP is criticized for it substantial complexity, with the necessity of serializing the remote call and then constructing a SOAP envelope to contain it. Due to the complexity of SOAP – REST (which doesn’t need a complex structure) is becoming a more popular way of providing and consuming web services.
REST
REST stands for Representational State Transfer, an emerging method to create and utilize web services. It is a simple yet powerful method of creating and consuming web services. REST is sometimes known as RESTful Web Services. RESTful web services uses HTTP or similar protocols by constraining the interface to the standard operation like GET, POST and PUT methods. REST focuses on interacting with stateful resources rather than messages or operations.
Two main principles of RESTful web services are:
- Resources are represented by URL. Resources can be thought of as an entity which the user can access as an API of a web service. Each resource in a REST application has a unique URL.
- Operations in RESTful Web Services are carried out by standard HTTP operations such as GET, POST and PUT.
Let’s look at an example to understand the REST principle. Suppose we’ve got a marketplace website where the merchant can upload, view and delete any product.
- Each Product detail can be accessed from a unique URL. Let’s suppose it is http://marketplace-website/product/123 and the HTTP GET method can be used to get the detail of the product from the above URL.
- HTTP POST method can be used to post a new product to the website with the detail specified by the server in a particular URL (specified by server and the server responses) with information regarding the product upload.
- HTTP DELETE method can be used to delete the particular product from the website using a unique URL for this operation.
XML-RPC
An XML-Remote Procedure call is another way of providing and consuming web services. XML-RPC uses XML to encode the request and response of the services and HTTP as a transport medium.
XML-RPC is a very simple protocol for using and consuming web services. It has a definite set of XML formats for defining the procedure, the data type and the commands. XML-RPC is designed to be as simple as possible, while allowing complex data structures to be transmitted, processed and returned. Let’s look at an XML format for calling a remote procedure.
<?xml version="1.0"?> <methodCall> <methodName>examples.getProductName</methodName> <params> <param> <value><int>10</int></value> </param> </params> </methodCall>
Now, let’s look at the response of the above call in XML format:
<?xml version="1.0"?> <methodResponse> <params> <param> <value><string>Apple IPhone 3G</string></value> </param> </params> </methodResponse>
JSON
XML is the dominant data representation and interchange format on the web, but nowadays, another data type interchange format is picking up the hype - and it is JSON (JavaScript Object Notation). A main benefit of JSON over XML is that JSON is lightweight data interchange format. JSON defines the data structures in the form of associative arrays commonly called Objects in its representation.
The file extension of JSON data representation is .json and Internet media type text/json is reserved for representing JSON data. JSON data is primarily used in the Ajax applications where it serves as the alternative for XML data.
As the name specifies, JSON is a subset of JavaScript and whilst commonly used with JavaScript, it is a language independent data format and can therefore be used with other languages as well.
The following example shows the JSON representation of the person object.
{ "firstName": "Michael", "lastName": "Johnson", "address": { "postalCode": 12345, "city": "New York", "state": "NY", "country": "USA" }, "phoneNumbers": [ "217 390-4455", "644 224-599" ] }
As you can see above JSON representation, “address” element contains another four elements named “postalCode”, “city”, “state” and “country”. Furthermore, the “phoneNumbers” element contains two phones numbers stored in array. You can see the detail of JSON representation from http://json.org.
Now, let’s look at quickly how can we parse JSON data using JavaScript. Let’s suppose that above JSON data representing a person object is contained in json_data string variables in JavaScript:
Var json_data=’{ "firstName": "Michael", "lastName": "Johnson", "address": { "postalCode": 12345, "city": "New York", "state": "NY", "country": "USA" }, "phoneNumbers": [ "217 390-4455", "644 224-5994" ] }’;
Note that there should not be any line break in the above string otherwise the JSON representation can’t be parsed by JavaScript. To have a clear vision about the object, it is displayed above in a well formatted manner.
Now, we can use the eval() function of JavaScript to parse the JSON data in the following way:
var person=eval("("+json_data+")");
Now, you can access all the fields of JSON data using the person variable. The variable person.firstNamereturns “John”, person.address.city returns “New York” and person..phoneNumbers[0] returns “217 390-4455”.
Until now, we’ve looked at various technologies for creating and using web widget. Now, let’s create a really simple web widget to display Packt’s logo.
Web Widget to Display Logo
Now, we’re going to create a web widget which displays the small logo of Packt Publishing (http://www.packtpub.com). You’ll have to place a line of JavaScript code in the remote website where you want to display this small logo.
You could simply place html code <img src=”http://images.packtpub.com/images/PacktLogoSmall.png” /> to display the small logo of PACKT Publishing. But, I’m using this example to show how to use JavaScript to achieve the same thing so that it will be easier for you to understand the more complex JavaScript application
What does it look like?
As you can see from the above image, this widget will just display the Packt logo.
JavaScript Code
For creating the web widget that displays the logo, use the following JavaScript Code.
document.write("<img style='margin:5px' src= 'http://images.packtpub.com/images/PacktLogoSmall.png' />");
You’ll need to write the code in a file (e.g. image-widget.js). The above code displays the logo with the added margin of 5 pixels in the document.
The above margin attribute adds margin of 5 pixels in all four side of image element. You can specify different margin for different sides by:
margin: 2px 3px 4px 5px;
This adds the margin of 2 pixel, 3pixel, 4 pixel and 5 pixel in top, right, bottom and the left hand sides of the element respectively.
margin: 2px 3px 4px 5px;
This adds the margin of 2 pixel, 3pixel, 4 pixel and 5 pixel in top, right, bottom and the left hand sides of the element respectively.
Using Logo web widget
To use the web widget we’ve to follow these steps:
- First of all, we need to upload the above image-widget.js to a web server so that it can be used by the client websites. Let’s suppose that is uploaded and placed in the URL :http://www.widget-server.com/image-widget.js
- Now, we can widget in any web pages by placing the following JavaScript Code in the website.
<script type="text/javascript" language="javascript" src="http://www.widget-server.com/image-widget.js"></script>
We’ve provided the source of the script element to the JavaScript file which contains the JavaScript code to write the “img” tag to the document which uses that code.
Summary
Web Widgets are basically used for providing and serving the functionality of a remote website. The client’s website places a small chunk of code to serve the functionality provided by the widget providers.
We have covered the various technologies that go behind making a Widget work, such as, CSS, JavaScript, XML, PHP, AJAX, and web services. In the next article we will develop a wiki seek widget using Javascript.
If you have read this article you may be interested to view :
No comments:
Post a Comment