hientx

Just another WordPress.com site

convert xml file to string xml, convert string xml to document and convert string to InputStream

import java.io.ByteArrayInputStream;

04.import java.io.InputStream;
05.import java.io.UnsupportedEncodingException;
07.public class StringToStream {
08.    public static void main(String[] args) {
09.        String text = "Converting String to InputStream Example";
16.        try {
17.            InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
18.        } catch (UnsupportedEncodingException e) {
19.            e.printStackTrace();
20.        }
21.    }
22.}

Convert XML file to XML String in java

I had to find out a way to read an XML file, and convert it to java String. Below is the code snippet I used.

public String convertXMLFileToString(String fileName)
{
try{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
InputStream inputStream = new FileInputStream(new File(fileName));
org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
StringWriter stw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.transform(new DOMSource(doc), new StreamResult(stw));
return stw.toString();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}

Convert String XML to XML Document in java

Example 1: Element node =  DocumentBuilderFactory     .newInstance()     .newDocumentBuilder()     .parse(new StringInputStream("<node>value</node>"))     .getDocumentElement(); Example 2: 
/**    * @param docBuilder    *          the parser    * @param parent    *          node to add fragment to    * @param fragment    *          a well formed XML fragment    */   public static void appendXmlFragment(       DocumentBuilder docBuilder, Node parent,       String fragment) throws IOException, SAXException {     Document doc = parent.getOwnerDocument();     Node fragmentNode = docBuilder.parse(         new InputSource(new StringReader(fragment)))         .getDocumentElement();     fragmentNode = doc.importNode(fragmentNode, true);     parent.appendChild(fragmentNode);   } 
Example 3: 

Then get the Document into which the new node is inserted, and the parent Element (to be) from it. (Your org.w3c.dom.Document would need to be converted to org.dom4j.Document here.) For testing purposes, I created one like this:

    Document originalDoc =       new SAXReader().read(new StringReader("<root><given></given></root>"));     Element givenNode = originalDoc.getRootElement().element("given"); 

Adding the new child element is very simple:

    givenNode.add(newNodeDocument.getRootElement()); 

Done. Outputting originalDoc now yields:

<?xml version="1.0" encoding="utf-8"?> <root>     <given>         <node>value</node>     </given> </root> 

Appendix: Because your question talks about org.w3c.dom.Document, here’s how to convert between that and org.dom4j.Document.

// dom4j -> w3c DOMWriter writer = new DOMWriter(); org.w3c.dom.Document w3cDoc = writer.write(dom4jDoc); // w3c -> dom4j DOMReader reader = new DOMReader(); Document dom4jDoc = reader.read(w3cDoc); 
 Source: http://stackoverflow.com/questions/729621/convert-string-xml-fragment-to-document-node-in-java
 http://sacrosanctblood.blogspot.com/2008/07/convert-xml-file-to-xml-string-in-java.html 

array 2, 3, multi dimention in javascript

Example 1

var x = new Array(
new Array(
new Array(“hehe”, “hoho”, “haha”),
new Array(“tenten”, “tintin”, “lala”)),
new Array(
new Array(“hihi”, “haha”),
new Array(“kaka”, “titi”))
);

alert(x[1][1][1]);  // returns ‘titi’

Example 2

If you have a structure like this one

var provinces = [
{ name: “Province A”, cities: [
{ name: “City A.A”, malls: [
{ name: “Mall A.A.1” },
{ name: “Mall A.A.2” }
] },
{ name: “City A.B”, malls: [
{ name: “Mall A.B.1” }
] }
] },
{ name: “Province B”, cities: [
{ name: “City B.A”, malls: [
{ name: “Mall B.A.1” },
{ name: “Mall B.A.2” }
] },
{ name: “City B.B”, malls: [] }
] }
];

Then you can populate the dropdowns like so:

function populateDropdown(drop, items) {
drop.empty();
for(var i = 0; i < items.length; i++) {
drop.append(‘<option value=’ + i + ‘>’ + items[i].name + ‘</option>’);
}
drop.show();
}

populateDropdown( $(‘#provinces’), provinces );

And upon an action:

$(‘#provinces’).change(function() {
var provinceIndex = $(this).val();
var province = provinces[provinceIndex];

populateDropdown( $(‘#cities’), province.cities );

$(‘#malls’).hide();
});

$(‘#cities’).change(function() {
var provinceIndex = $(‘#provinces’).val();
var province = provinces[provinceIndex];

var cityIndex = $(this).val();
var city = province.cities[cityIndex];

populateDropdown( $(‘#malls’), city.malls );
});

EDIT

If the data structure on top looks hard to read, by the way, it’s the exact same thing as the following:

var provinces = [];

// populate provinces
provinces.push({ name: “Province A”, cities: [] });
provinces.push({ name: “Province B”, cities: [] });

// populate cities
provinces[0].cities.push({ name: “City A.A”, malls: [] });
provinces[0].cities.push({ name: “City A.B”, malls: [] });
provinces[1].cities.push({ name: “City B.A”, malls: [] });
provinces[1].cities.push({ name: “City B.B”, malls: [] });

// populate malls
provinces[0].cities[0].malls.push({ name: “Mall A.A.1” });
provinces[0].cities[0].malls.push({ name: “Mall A.A.2” });
provinces[0].cities[1].malls.push({ name: “Mall A.B.1” });
provinces[1].cities[0].malls.push({ name: “Mall B.A.1” });
provinces[1].cities[0].malls.push({ name: “Mall B.A.2” });

read write XML with JavaScript

XML and JavaScript Tutorial

XML and JavaScript

                                                                                                                            – Premshree Pillai

 

Introduction:
XML is a very important base on which Web Services work. XML can be used in conjunction with a lot of client side and server side languages to put it to good effect.

Let us see how we can use XML and client side JavaScript to work. We will see how we can display the contents of a XML file using JavaScript, accessing child elements, manipulating elements etc.

Browser Issues:

When it comes client side languages browser incompatibilities is a major issue. But here where we want to use XML and JavaScript, XML is the issue. Not all browsers have support for parsing XML documents. I will use IE6 to explain the codes. Browsers that do not support XML, cannot read them. When you view an XML file in such a browser it will just ignore all the tags.

Sample XML file:

Let us consider a sample XML file >>

<?xml version=”1.0″ ?>

<company>

<employee id=”001″ sex=”M” age=”19″>Premshree Pillai</employee>

<employee id=”002″ sex=”M” age=”24″>Kumar Singh</employee>

<employee id=”003″ sex=”M” age=”21″>Ranjit Kapoor</employee>

<turnover>

<year id=”2000″>100,000</year>

<year id=”2001″>140,000</year>

<year id=”2002″>200,000</year>

</turnover>

</company>

The above XML file shows employee data and Turnover of the company (just an e.g).

Manipulating XML file data using JavaScript:

 

·         Loading XML file: You can load a XML fie from JavaScript like this >>

var xmlDoc = new ActiveXObject(“Microsoft.XMLDOM”);
function loadXML(xmlFile)
{
xmlDoc.async=”false”;
xmlDoc.onreadystatechange=verify;
xmlDoc.load(xmlFile);
xmlObj=xmlDoc.documentElement;
}

Actually, just the last two lines of the function are enough to load the XML file. The previous two lines are written to ensure that the JavaScript functions that we may use later to manipulate the XML file data, does not perform any function on an uninitialized object. Thus the function verify()is called.
function verify()
{
// 0 Object is not initialized
// 1 Loading object is loading data
// 2 Loaded object has loaded data
// 3 Data from object can be worked with
// 4 Object completely initialized
if (xmlDoc.readyState != 4)
{
return false;
}
}

Now the XML file can be loaded

loadXML(‘xml_file.xml’);

 

·         Displaying contents of XML file: View the entire contents of the XML file using alert(xmlObj.xml);
The entire XML file will be displayed in an alert box as it is with proper indentation.

 

·         Children and nodes: In the above XML file <company> is the top level tag under which all other tags come. These tags are called children. The above XML file can be represented graphically like a folder-tree. A folder-tree is shown below.

·

Thus in the above XML file the top level tag <company> has 4 children.

The numbering of children (as is usual in all languages) starts from 0 (zero).

The <turnover> tag has 3 children under it.

We can find the no of children a tag has by using the childNodes.length property. Thus the no of childen   of <company> tag (here, 4) can be found by using xmlObj.childNodes.length

The no of children of <turnover> tag (here, 3) can be found by using xmlObj.childNodes(3).childNodes.length

Here we use childNodes(3) because <turnover> is the 3rd child of <company>

·         Testing for children: You can test whether a particular node child has any children using childNodes(i).hasChildNodes
Thus xmlObj.childNodes(3).hasChildNodes() will return true.
xmlObj.childNodes(2).hasChildNodes() will return false, since the <employee> tag does not have any children.

·         Getting Tag Name: You can get the tag name of a child using childNodes(i).tagName. Thus xmlObj.tagName will return “company”.
xmlObj.childNodes(0).tagName will return “employee”.
xmlObj.childNodes(3).childNodes(0).tagName will return “year”.

 

·         Displaying content of a tag : In the XML file the content of the 1st <employee> tag is “Premshree Pillai”. You can get this value using xmlObj.childNodes(0).firstChild.text
xmlObj.childNodes(2).firstChild.text will return “Suhasini Pandita”.
Similarly xmlObj.childNodes(3).childNodes(1).firstChild.text will return “140,000”.

·         Attributes : In the XML file, the <employee> tag has 3 attributes. An attribute can be accessed using childNodes(i).getAttribute(“AttributeName”). Thus xmlObj.childNodes(0).getAttribute(“id”) will return “001”.
xmlObj.childNodes(1).getAttribute(“age”) will return “24”.
xmlObj.childNodes(2).getAttribute(“sex”) will return “F”.


XML – JavaScript Example:
There are many more properties and methods available. Using these properties you can create lots of client side applications. The main advantage of using XML along with JavaScript is that editing of data becomes very easy. XML being structured, it becomes very easy to manage content. One example is a folder-tree menu. Another one is a JavaScript Ticker. You can find a XML based JavaScript Ticker at

 

http://www.dynamicdrive.com/dynamicindex2/xmlticker.htm

 

XML based JavaScript Ticker :

We will create a XML based JavaScript Ticker that can tick any number of messages. The ticker reads it’s contents, i.e the ticker style, text to be displayed, the link for that particular message from a XML file. Let the XML file be ticker_items.xml

The structure of the XML document is as follows >>

TICKER

  tickerstyle

        » pause = “true” / “false” :: “true” for pause onMouseOver

        » timeout = any integer :: The delay in seconds between different messages.

        » border = any integer :: Border width of Ticker

        » bordercolor = #HexColor :: The border color of Ticker

        » background = #HexColor :: Background color of Ticker

        » width = any integer :: Ticker width

        » height = any integer :: Ticker height

          tickerlinkstyle

          mouseout

                  » font = “verdana,arial,helvetica…..” :: Ticker link font

                  » color = #HexColor :: Ticker link color

                  » decoration = “none” / “underline” / “underline + overline” :: Ticker link style

                  » weight = “normal” / “bold” :: Ticker link weight

                  » size = ‘any integer’pt :: Ticker link size

           mouseover

                  » font = “verdana,arial,helvetica…..” :: Ticker link font

                  » color = #HexColor :: Ticker link color

                  » decoration = “none” / “underline” / “underline + overline” :: Ticker link style

                  » weight = “normal” / “bold” :: Ticker link weight

                  » size = ‘any integer’pt :: Ticker link size

 tickeritem

                » URL = A valid URL :: Ticker link URL

                » target = “_blank” / “_top” / “_self” / ‘any other valid target name’ :: Ticker link target

 

XML Ticker Script :

<script language=”JavaScript1.2″>

// XML Ticker JavaScript

// (c) 2002 Premshree Pillai

// http://www.qiksearch.com

// Use freely as long as all messages are as it is

// Location of script : http://www.qiksearch.com/javascripts/xml/ticker.htm

var xmlDoc = new ActiveXObject(“Microsoft.XMLDOM”);

function loadXML(xmlFile)

{

xmlDoc.async=”false”;

xmlDoc.onreadystatechange=verify;

xmlDoc.load(xmlFile);

ticker=xmlDoc.documentElement;

}

function verify()

{

if (xmlDoc.readyState != 4)

{

return false;

}

}

loadXML(‘ticker_items.xml’);

document.write(‘<style type=”text\/css”>’);

document.write(‘.ticker_style{font-family:’ + ticker.childNodes(1).childNodes(0).getAttribute(‘font’) + ‘; font-size:’ + ticker.childNodes(1).childNodes(0).getAttribute(‘size’) + ‘; color:’ + ticker.childNodes(1).childNodes(0).getAttribute(‘color’) + ‘; font-weight:’ + ticker.childNodes(1).childNodes(0).getAttribute(‘weight’) + ‘; text-decoration:’ + ticker.childNodes(1).childNodes(0).getAttribute(‘decoration’) + ‘}’);

document.write(‘.ticker_style:hover{font-family:’ + ticker.childNodes(1).childNodes(1).getAttribute(‘font’) + ‘; font-size:’ + ticker.childNodes(1).childNodes(1).getAttribute(‘size’) + ‘; color:’ + ticker.childNodes(1).childNodes(1).getAttribute(‘color’) + ‘; font-weight:’ + ticker.childNodes(1).childNodes(1).getAttribute(‘weight’) + ‘; text-decoration:’ + ticker.childNodes(1).childNodes(1).getAttribute(‘decoration’) + ‘}<br>’);

document.write(‘</style>’);

document.write(‘<table style=”border:’ + ticker.childNodes(0).getAttribute(‘border’) + ‘ solid ‘ + ticker.childNodes(0).getAttribute(‘bordercolor’) + ‘; background:’ + ticker.childNodes(0).getAttribute(‘background’) + ‘; width:’ + ticker.childNodes(0).getAttribute(‘width’) + ‘; height:’ + ticker.childNodes(0).getAttribute(‘height’) + ‘”><tr><td><div id=”ticker_space”></div></td></tr></table>’);

var item_count=2;

var timeOutVal=(ticker.childNodes(0).getAttribute(‘timeout’))*1000;

var original_timeOutVal=timeOutVal;

var isPauseContent;

if(ticker.childNodes(0).getAttribute(‘pause’)==”true”)

{

isPauseContent=’ onmouseover=”setDelay();” onmouseout=”reset();”‘;

}

else

{

isPauseContent=”;

}

function setTicker()

{

document.all.ticker_space.innerHTML='<center><a href=”‘ + ticker.childNodes(item_count).getAttribute(‘URL’) + ‘” target=”‘ + ticker.childNodes(item_count).getAttribute(‘target’) + ‘” class=”ticker_style”‘ + isPauseContent + ‘>’ +   ticker.childNodes(item_count).firstChild.text + ‘</a></center>’;

if(item_count==ticker.childNodes.length-1)

{

item_count=2;

}

else

{

item_count++;

}

setTimeout(“setTicker()”,timeOutVal);

}

function setDelay()

{

timeOutVal=10000000000000;

item_count–;

}

function reset()

{

timeOutVal=original_timeOutVal;

setTicker();

}

setTicker();

</script>

As you can see in the source code, the ticker reads all the contents/messages to be displayed, the links for each message, the target for each URL, the ticker static style, roll-over style, border width, color, background, the delay between messages etc from the XML file. So if you want to change any parameter of the Ticker, all you have to do is make necessary changes in the XML file.

The ticker shown here is a basic ticker that rotates messages at an interval that is specified in the XML file. There are many effects you could add to the ticker like ‘Fading message’, ‘Teletypewriter’. You could add features to change the ticker speed or to list all messages at an instant.

You can find some Ticker effects at

http://www.qiksearch.com/javascripts.htm

 I hope this article has helped you in some way.

Source: http://www.codetoad.com/xml_javascripti_tutorial.asp

Notes from Scaling MySQL – Up or Out

Here is the quick notes from the session Scaling MySQL – Up or Out ? moderated by Kaj Arno as part of the todays keynote.

Here is the list of panelists are ordered by Alexa ranking.

  1. Monty Taylor (MySQL)
  2. Matt Ingerenthron (Sun)
  3. John Allspaw (Flickr)
  4. Farhan Mashraqi (Fotolog)
  5. Domas Mituzas (Wkipedia)
  6. Jeff Rotheschild (Facebook)
  7. Paul Tuckfield (YouTube)

Here is the list of questions and answers from panelists:

 How many servers Number of DBAs How many web servers Number of caching servers Version of MySQL Language, platform Operating System
MySQL 1 M, 3 S 1/10 2 2 5.1.23 Perl,php and bash Linux fedora
Sun 2 clustered, 2 individual 1.5 160+ 8 5.0.21 Lots of stuff (java mostly) Open Solaris
Flickr 166 At present 0 244 14 5.0.51 Php and some Java Linux
Fotolog 140 databases on 37 instances 10 instances a DBA 70 40 ( 2 on each, 80 total) 4.11 and 4.4 Php, 90% Java Solaris 10
Wikipedia 20 None, but everybody is kind of a  DBA 70+200 40 ( 2 on each, 80 total)  Php, c++, python Fedora / Ubuntu
Facebook 30000 databases, 1800 db servers 2 1200 805 5.0.44 with relay log corruption patch Php, python, c++ and erlang Fedora / RHEL
Youtube I can not say 3 I can not say  I can not say  5.0.24 Python SuSE 9

Few more misc questions …

Number of times re-architected ?

  • My: 2 times – 1 time slave, 1 time memcached
  • SN: site depend (many times over the year)
  • FR: 2.5 (various clusters federated)
  • FL: many cached replacements (about to do one change now)
  • WK: Never (Spaghetti)
  • FB: Every Tuesday, continual
  • YT: Pretty continual, 2-3 times (replication, sharding, federation)

What happens if server fails ? what actions you will generally take ..

  • FR: All of our servers are federated, pairs of servers, we can loose any one side of shard, we can loose boxes.. traffic goes to either side of shard, now it goes to one, and we will get another one (very transparent to user)
  • WK: Users shout at them on IRC then they moderate … fixed in seconds
  • FB: one of 1800-1900 will always fail, just operate well, minor impact, with data going away for a while…we restore from binlog and start the server quickly, promote slave to master and number of ways
  • FL: we simply mount the snapshots to different servers and get
  • YT: SAN etc, very important data.. recover the server, mirrored disk …mirrored hard drive is crucial

Any recommendation of scaling technology that you wanted to bring

  • FL: UltraSPARC-T1 (excellent master, multi threaded) and UltraSPARC-T2 for slave (single threaded)
  • WK: good network switch
  • FB: cheap switch causes problems and learned lessons, we do not use SAN, neatly partitioned, they scale independently and fail independently
  • MY: cluster very sad

Server virtualization ?

  • nobody uses at this time
  • FB: ETL cluster, we may run more than one in the future

Anything to worry at present ?

  • FB: app design is the key to use resources, data center power supply and consumption
  • FL: Google has to approve for our lab power (cut app servers by 1/2 by moving from php to java)
  • YT: not at all

Any reco, lessons to DBA

  • better you know what the systems are, then you can
  • performance, scaling taking it serious
  • nothing more permanent than temp solutions (if you don’t know when you will fail, then you will )
  • architect properly in start, schema, cost of serving data

Source: http://venublog.com/2008/04/16/notes-from-scaling-mysql-up-or-out/

Some Frameworks JS

Hello Jsp and Ajax

Simple Ajax script for JSP

Lot of script is available for auto complete, load page, validation, and menu navigation in Ajax which can use in JSP.

A simple example of ajax show you to use in JSP

index.jsp

<html>
<head>
<script src=”ajaxjs.js”></script>
</head>
<body>
<a href=”javascript:loadContent(‘parameterValue’)”>Load Ajax content</a>
<div id=”prtCnt”></div>

</body>
</html>

ajaxjs.js

var xmlhttp

function loadContent(str)
{

xmlhttp=GetXmlHttpObject();

if (xmlhttp==null)
{
alert (“Your browser does not support Ajax HTTP”);
return;
}

var url=”loadJSP.jsp”;
url=url+”?q=”+str;

xmlhttp.onreadystatechange=getOutput;
xmlhttp.open(“GET”,url,true);
xmlhttp.send(null);
}

function getOutput()
{
if (xmlhttp.readyState==4)
{
document.getElementById(“prtCnt”).innerHTML=xmlhttp.responseText;
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject(“Microsoft.XMLHTTP”);
}
return null;
}

JSP file which load in background

loadJSP.jsp

<%@ page contentType=”text/html; charset=iso-8859-1″ language=”java” %>
<%
String q =request.getParameter(“q”);
String str=”This is JSP string loading from JSP page in ajax, loading time :”;
java.util.Date dt=new java.util.Date();
out.print(str+dt);
%>

source: easywayserver

Use english in windows 7

Ức chế vãi chưởng với việc sử dụng tiếng Pháp trên máy tính. Bàn phím đã chuyển thành tiếng Anh lâu rồi, nhưng ngôn ngữ trong hệ điều hành vẫn chưa chuyển được. Tìm cái IIS services cứ phải loay hoay mãi. Shit. Cả cái thế giới này nó dùng Tiếng Anh, cái thằng Pháp  này thật loằng ngoằng.

Sau một hồi tìm kiếm và có kết luận như sau:

– Bản windows 7 ultimate và entreprise mới có thể sử dụng đa ngôn ngữ.

– Bản Windows 7 Professional và Home ko có chức năng đa ngôn ngữ. Mà muốn upgrade lên bản ultimate thì phải mất hơn 100$. Như vậy có nghĩa là ko thể làm đc gì trừ khi cài lại win, nhục thật. Vậy là phải chung sống với tiếng Pháp trên máy tính rồi.

Introduce Json

Recently, JSON (JavaScript Object Notation) has become a very popular data interchange format with more and more developers opting for it over XML. Even many web services nowadays provide JSON as the default output format.

JSON is a text format that is programming-language independent and is a native data form of JavaScript. It is lighter and faster than XML because it needs less markup compared to XML.

Because JSON is the native data form of JavaScript, it can be used on the client side in an AJAX application more easily than XML.

A JSON object starts with { and ends with }. According to the JSON specification, the following types are allowed in JSON:

– Object: An object is a collection of key-value pairs enclosed between { and } and separated by a comma. The key and the value themselves are separated using a colon (:). Think of objects as associative arrays or hash tables. Keys are simple strings and values can be an array, string, number, boolean, or null.

– Array: Like other languages, an array is an ordered pair of data. For representing an array, values are comma separated and enclosed between [ and ].

– String: A string must be enclosed in double quotes

– The last type is a number

A JSON can be as simple as:
{
“name”:”Superman”, “address”: “anywhere”
}
An example using an array is as follows:
{
“name”: “Superman”, “phoneNumbers”: [“8010367150”, “9898989898”,
“1234567890” ]
}

A more complex example that demonstrates the use of objects, arrays, and values is as follows:
{
“people”:
[
{
“name”: “Vijay Joshi”,
“age”: 28,
“isAdult”: true
},
{
“name”: “Charles Simms”,
“age”: 13,
“isAdult”: false
}
]
}

An important point to note:

{
‘name’: ‘Superman’, ‘address’: ‘anywhere’
}
Above is a valid JavaScript object but not a valid JSON. JSON requires that the name and value must be enclosed in double quotes; single quotes are not allowed.

Remember that JSON expects the data to be UTF-8 whereas PHP adheres to ISO-8859-1 encoding by default

Also note that JSON is not a JavaScript; it is basically a specification or a subset derived from JavaScript.

AJAX XMLHttpRequest

– File HelloAjaxHttpRequest.html

<html>
<head>
<title>Aborting ajax requests</title>
<style type=”text/css”>
ul{border:1px solid black; list-style:none;
margin:0pt;padding:0pt;float:left;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;width:300px;}
li{padding:10px 5px;border-bottom:1px solid black;}
</style>

<script type=”text/javascript” src=”../js/jquery.js”></script>
<script type=”text/javascript”>
$(document).ready(function ()
{
var ajax;
$(‘#choice’).change(function()
{
if(ajax)
{
ajax.abort();
}
ajax = $.get(
            ‘wait.php’,
            { what : $(this).val() },
            function(response)
            {
              $(‘#response’).html(response);
            },
            ‘html’
          );
});
});
</script>

</head>
<body>
<form>
<p>
Show list of:
<select id=”choice”>
<option value=””>select</option>
<option value=”good”>Good Guys</option>
<option value=”bad”>Bad Guys</option>
</select>
</p>
<p id=”response”></p>
</form>
</body>
</html>

– File wait.php

<?php
  sleep(2);
if($_GET[‘what’] == ‘good’)
{
$names = array(‘Sherlock Holmes’, ‘John Watson’, ‘Hercule
Poirot’, ‘Jane Marple’);
echo getHTML($names);
}
else if($_GET[‘what’] == ‘bad’)
{
$names = array(‘Professor Moriarty’, ‘Sebastian Moran’,
‘Charles Milverton’, ‘Von Bork’, ‘Count Sylvius’);
echo getHTML($names);
}
function getHTML($names)
{
$strResult = ‘<ul>’;
for($i=0; $i<count($names); $i++)
{
$strResult.= ‘<li>’.$names[$i].'</li>’;
}
$strResult.= ‘</ul>’;

return $strResult;
}
?>

All AJAX methods of jQuery return an XMLHttpRequest object when called. We have declared a global variable ajax that will store this object. When a value is selected from the combo box, the handler function checks if the variable ajax is defined or not. In case of the first selection it will be undefined, hence nothing happens and the request is sent to the wait.php file. The XMLHttpRequest object created for sending this request is stored in variable ajax.

Now when a value of combo box is changed ajax will be holding the XMLHttpRequest object that was used to send the previous request. XMLHttpRequest has an abort() method that cancels the current request. In our case the pending request to the server is cancelled and a new request is made, which is again stored in the ajax variable.

Compare Post and Get

$.post() is almost similar to $.get() except for a couple of differences. The first, and obvious difference, is the method used which is POST for $.post() and GET for $.get(). The second difference is that POST requests are not cached whereas GET requests are cached by the browser. Therefore, the use of the cache option with POST request will have  no effect on the request.

Other than that, both $.get() and $.post() have the same signatures.