Home > AJAX Examples and Tutorials > How to use XMLHttpRequest
India still ‘world class’ insists Mathews
SL to market Ayurveda drugs
Nine hand grenades found near Aluth Kade Court
Hirunika to join active politics
IPL teams splash the cash for Mahela and Murali
Anoma to lead protest to free SF
US diplomats heading to Sri Lanka
CID probing double murder in Kahawatta
Dr. R.H.S. Samaratunga appointed Sec to Petroleum Ministry
A/L fiasco - Probe team’s mandate limited
Three including police officer injured in Maligawatta shootout
External degrees are worthless says Minister S.B. Dissanayke
SL rules out currency devaluation in 2012
මාළිගාවත්තේ වෙඩි තැබීමක් -තිදෙනෙකුට තුවාලයි
ක්රිකට් මුල් පුටුව උපාලි ධර්මදාසට
Accidents on the rise as New Year dawns
CAA yet to act on gas price revision
38 students yet to receive A/L results - CTU
நாடாளுமன்ற தெரிவுக்குழுவை நாம் முற்றாக நிராகரிக்கவில்லை - சம்பந்தன்
மட்டு புதுவருட கொண்டாட்டங்கள்
Are you in Love?
10 Top Sex Secrets Men won't Tell
Top 10 — Female Turn Ons
10 Commandments for good wives
How to live a happy and satisfied Life
Did I marry the right person?
Are You Happy
Alcohol makes men BETTER in the bedroom, scientists claim
Too busy for Love Making?
Have you gone off sex?
Love Isn't Blind
Are You A Lazy Lover?
5 Secret Relationship Resolutions
Are You Getting Attracted To Another Person?
Do you feel loved?
How to use XMLHttpRequest
Sample javascript implementing a cross platform xmlhttprequest function:
Sample javascript implementing a cross platform xmlhttprequest function:
- Method 1 – Public domain XMLHttpRequest Object1
- Method 2 – XHConn, CC-SA XMLHttpRequest Object2 Returning Content Through XMLHttpRequest3
Method 1
In this method, you can instantiate an XMLHttpRequest object that can then call functions from the server. The code is in the public domain.
function getNewHTTPObject()
{
var xmlhttp;
/** Special IE only code ... */
/*@cc_on
@if (@_jscript_version >= 5)
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/
/** Every other browser on the planet */
if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
Now you can call XMLHTTPRequest
var xmlHttp = getHTTPObject();
function getDynamicData()
{
var url = "http://url/that/returns/dynamic/content";
xmlHttp.open('GET', url, true);
xmlHttp.onreadystatechange = callbackFunction;
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.send(null);
}
The callback function set in xmlHttp.onreadystatechange will be called when data is back from the server
var syndLinkRequest = getNewHTTPObject();
function callbackFunction()
{
if (syndLinkRequest.readyState != 4)
return;
var result = xmlHttp.responseText;
/* if you've returned javascript instead of xml or text,
you can eval(result) to access the javascript variables returned.
*/
}
Method 2 – XHConn
XHConn is an open source project that attempts to create a very simple and cross platform way to invoke Ajax requests
/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08 **
** Code licensed under Creative Commons Attribution-ShareAlike License **
** http://creativecommons.org/licenses/by-sa/2.0/ **/
function XHConn()
{
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) return null;
this.connect = function(sURL, sMethod, sVars, fnDone)
{
if (!xmlhttp) return false;
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET")
{
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else
{
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && !bComplete)
{
bComplete = true;
fnDone(xmlhttp);
}};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
Using XHConn:
//initialize XHConn (if XHConn isn't created successfully,
//the client doesnt' support Ajax)
var ajaxConn = new XHConn();
//post to mypage.php with args foo and baz
ajaxConn.connect("mypage.php", "POST",
"foo=bar&baz=qux",fnWhenDone);
//when the server responds, javascript
//will trigger this callback function
fnWhenDone(XML)
{
alert(XML.responseText);
}
Returning content through the XMLHTTPRequest method:
There are various ways you can return content through XMLHTTPRequest:- Plain text (XML.responseText)
- Javascript variables (eval(XML.responseText))
- JSON – Javascript objects (eval(XML.responseText))
- XML (XML.responseText = XML)
Of these, plain text is the simplest, as all it requires is servicing a request with a simple plain text dump of data. The downside to this method is that it’s not always a clean way to return more than one variable.
Javascript variables are a nice way to return multiple variables through an XMLHTTPRequest call. Instead of dumping plain text, the server decorates the different returned variables with javascript variable declarations. On the client end, the XMLHTTPRequest callback function evals the server response and now has the variables set by the server available to it as native javascript variables.
One key part of this method however is remembering to escape the content in the javascript variable assignment.
The third way of passing back content through XMLHTTPRequest is XML, which despite the name of the function, is often the slowest and most difficult way due to difficulties parsing xml. However for highly structured content or when E4X becomes more standard, this might be the way to go.
Guidelines: You must register with a social media account such as Facebook, Twitter, Yahoo, etc. to comment on this story. Click on the "Login" button below to choose your login account of choice. We welcome your thoughts, but this is not an open forum. For the sake of all readers, please refrain from the use of obscenities, personal attacks or racial slurs. All comments must remain on topic and cyber bullying will not be tolerated. All comments are subject to our terms of service. Comments that do not comply may be removed. Repeat offenders will lose commenting privileges.
News Categories
Accidents and Incidents
Art and Society
Business and Finance
Education and Employment
Environment and Development
Help and Aid
Science and Technology
Security and Politics
Share Market and Exchange Rates
Sports and Entertainment
Tourism and Foreign Affairs
Women and Health
Information
Women and Health
Food Recipes
Love and Relationship
Web and IT
AJAX Examples and Tutorials
Java Scripts Examples and Tutorials
PHP Scripts Examples and Tutorials
Men want good-looking women
Making sex exciting
Duminda unmasked by Anarkali
Too busy for Love Making?
Srikanth Vandana got a Baby Boy-Father and Son Born on Same Day!
Anjali’s days with Bharathiraja and K. Balachandar
Have you gone off sex?
Sex and Shoes
Dirty Talk!
Happy Birthday Surya
Alcohol makes men BETTER in the bedroom, scientists claim
Sexless Marriages
Are You A Lazy Lover?
5 Secret Relationship Resolutions
Outsider Played Actress Sneha Hot Sexy Hip Cheap Photos?

































