// reusable XMLHttpRequest object
var http = function() {
return ('XMLHttpRequest' in window)
? new XMLHttpRequest()
: (('ActiveXObject' in window)
? new ActiveXObject("Msxml2.XMLHTTP")
: null);
}();
top
// IE requires that you use http.open BEFORE assigning this
http.onreadystatechange = function() {
if (http.readyState === 4) { // XMLHttpRequest code for "Done"
if (http.status === 200) { // HTTP status code for "OK"
// use http.responseText or http.responseXML here
}
}
};
top
// simple GET request
http.open("GET", "myPage.php", true); // false for synchronous (blocking)
http.send(null); // null is required here
// passing variables to PHP by modifying the URL
var name = escape("Your Name");
var age = 27;
var queryString = "?name=" + name + "&age=" + age;
http.open("GET", "myPage.php" + queryString, true);
http.send(null);
top
http.open("GET", "myPage.php", true);
/**
* Set headers after open() and before send().
* For a complete list of request headers, see:
* http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html
*/
http.setRequestHeader("User-Agent", "arguments.callee Custom UA");
http.setRequestHeader("Accept", "text/plain, text/html, text/xml");
http.send(null);
top
// gather form data
var name = escape(document.getElementById("form-name").value);
var address = escape(document.getElementById("form-address").value);
// build query string
var query = "?name=" + name + "&address=" + address;
// make AJAX request
http.open("POST", "myPage.php", true);
http.onreadystatechange = function() {};
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", query.length);
http.setRequestHeader("Connection", "close");
http.send(query); // not "null" as with GET requests
top
http.abort(); // it's that easy!
top
<?php
// gather POST (or GET) variables
foreach($_POST as $key => $value) {
$$key = $value; // note the double $$
/**
* Using the last POST example, this loop will
* create the variables $name and $address.
*/
}
/**
* ALWAYS sanitize user input immediately before using it.
* htmlspecialchars() for displaying on a webpage
* mysql_real_escape_string() when using a MySQL database
* filter_var() for more customizable sanitization
*/
echo htmlspecialchars("$name lives at $address!");
exit;
?>
top
<?php
header("Content-Type: text/xml; charset=utf-8");
echo '<?xml version="1.0" encoding="utf-8"?>
<root>
<name>HB</name>
<address>123 Any St.</address>
<root>
';
exit;
?>
<?php
// some older browsers don't recognize JSON, so serve plain text to them
$mime = preg_match("/application\/json/i", $_SERVER["HTTP_ACCEPT"]) ? "application/json" : "text/plain";
header("Content-Type: $mime; charset=utf-8");
echo '[{"name":"HB","address":"123 Any St."}]';
exit;
?>
<?php
header("Content-Type: text/html; charset=utf-8");
/**
* JavaScript may do something like this with the following response:
* document.getElementById("targetDiv").innerHTML = http.responseText;
*/
echo '<p>This paragraph was retrieved via AJAX!</p>';
exit;
?>
<?php
header("Content-Type: text/plain"); // useful for delimited data (CSV, etc.)
echo "1, HB Stone, 123 Any St.\n";
echo "2, Sample Name, 345 Another St.\n";
exit;
?>
top
var Http = function() {
var ReadyStates = {
UNINITIALIZED : 0,
OPEN : 1,
SENT : 2,
RECEIVING : 3,
DONE : 4
};
var Status = {
OK : 200,
MULTIPLE : 300,
FORBIDDEN : 403,
NOT_FOUND : 404,
SERVER_ERROR : 500
};
var http = function() {
return ('XMLHttpRequest' in window)
? new XMLHttpRequest()
: (('ActiveXObject' in window)
? new ActiveXObject("Msxml2.XMLHTTP")
: null);
}();
return {
isBusy: function() {
return ((http.readyState !== ReadyStates.UNINITIALIZED) && (http.readyState !== ReadyStates.DONE));
},
request: function(obj) {
if (typeof obj.url !== "string") {
return;
}
var orsc function() { // onreadystatechange
if (http.readyState === ReadyStates.DONE) {
switch(http.status) {
case Status.OK:
if (typeof obj.success == "function") {
obj.success.call(http, http, obj);
}
break;
// handle other cases here as desired
default:
if (typeof obj.failure == "function") {
obj.failure.call(http, http, obj);
}
}
}
};
var query = function() {
if (typeof obj.data !== "object") {
return "";
}
var q = "";
for (var i in obj.data) {
if (obj.data.hasOwnProperty(i)) {
q += (q.length) ? "&" : "";
q += encodeURIComponent(i) + "=" + encodeURIComponent(obj.data[i]);
}
}
return q;
}();
switch(obj.method) {
// implement other methods as desired (HEAD, PUT, DELETE, etc.)
case "GET":
http.open(obj.method, obj.url + "?" + query, true);
http.onreadystatechange = orsc;
http.send(null);
break;
case "POST":
http.open(obj.method, obj.url, true);
http.onreadystatechange = orsc;
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", query.length);
http.setRequestHeader("Connection", "close");
http.send(query);
break;
default:
return; // invalid or unsupported method
}
}
};
}();
Any time you want to perform a request, you can do something like this:
Http.request({
url: "weather.php",
method: "GET",
data: {
zipCode = "92261"
},
success: function(http) {
alert("Weather report: " + http.responseText);
},
failure: function(http) {
alert("AJAX call failed! Status code: " + http.status);
}
});
I'm a Front-End Engineer at Yahoo! working on the Mail and Messenger teams. I blog about web design and development topics including accessibility, usability, performance, and developing HTML / CSS / JavaScript applications on Appcelerator Titanium and Adobe AIR.
If you're a web developer, you might enjoy Jelo, my JavaScript library.
A few panoramic shots I took at SDCC 2010. #geek http://bit.ly/bwX6GB
JS version of Regex prime number checker:
function isPrime(n) {
return Array(n + 1).join("1")
.search(/^1?$|^(11+?)\1+$/) == -1;
}
Погрузился в пучину EcmaScript5, местами увлекательно, местами нудно =)
Modernizr http://ow.ly/18njQ1
A Collection of 20 HTML5 Video Players - a round-up of JavaScript and html5 alternatives to Flash-based media player... http://ow.ly/18njQ2
jQuery TOOLS - The missing UI library for the Web http://ow.ly/18njQ3
Contactable - A jQuery Plugin | the odin http://ow.ly/18njQ4
Giants vs Dodgers, sweet seats. http://twitpic.com/2ag9pa
@snookca That'll be fixed next week. I promise.
@snookca I was tryna not name names ;) But really that was just par for the course today, pretty hectic day. As I'm sure you know.
Who breaks major stuff after 4pm on Friday? On the last day of the sprint, no less. Tsk. (wasn't me)
Awesome live git tracker for teams: http://www.utsup.com/
RT @DerrenBrown: Blog post: Camera Software Lets You See Into the Past http://bit.ly/9kjVg5
10 invites to the new version of Digg: http://bit.ly/dqM8EV
Threaded vs Evented Servers, great look at the whats and whys. http://bit.ly/bDUEjn #geek
Nav, Context menus, "app-style" toolbars in sample chapter http://bit.ly/csTRY8 of new YUI book http://bit.ly/cJINoV
Add a side-mounted End Call button to your iPhone 4: http://bit.ly/cGxPBD #funny #geekAll original work on this site is covered by a Creative Commons Attribution 3.0 license unless otherwise specified.
You may share or use any code or images from this site in any manner, for free, so long as reasonable effort has been made to give credit where due.
The views expressed in the posts and comments on this blog do not necessarily reflect the views of Yahoo!