XMLHttpRequest
(XHR)
xhr = new XMLHttpRequest();
xhr.open('GET', 'assets/06/examples/xml.php', false);
xhr.send(null);
alert('I am outputted once the call has finished loading (5s delay)');
alert(xhr.responseText);
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
};
xhr.open('GET', 'assets/06/examples/xml.php', true);
xhr.send(null);
alert('I am outputted immediately (no delay)');
IXMLHTTPRequest
invented by Microsoft
MSXML
LibraryXMLHttpRequest
in GeckoXMLHttpRequest
Object and return the ActiveX Object
if (typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
throw new Error("This browser does not support XMLHttpRequest");
};
xhr = new XMLHttpRequest();
// rest of your code ....
http://api.ikdoeict.be/
from http://www.ikdoeict.be/
I've sent you each 300 buckeroos. In the form of a tricky Dick fun bill. Knock yourselves out!
Content-Type: text/xml
header, XHR will automagically parse the returned data as XML<?xml version="1.0" encoding="UTF-8"?>
<sample>
<course>WMD</course>
<lecturers>
<lecturer>Bramus Van Damme</lecturer>
<lecturer>Davy De Winne</lecturer>
</lecturers>
</sample>
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var xml = xhr.responseXML,
courseName = xml.getElementsByTagName('course')[0].firstChild.nodeValue,
lecturersXml = xml.getElementsByTagName('lecturer'),
lecturers = [];
console.log(xml);
for (var i = 0, len = lecturersXml.length; i < len; i++) {
lecturers.push(lecturersXml[i].firstChild.nodeValue);
}
alert('<p>' + courseName + ' is taught by ' + lecturers.join(' & ') + '</p>');
}
};
xhr.open('GET', 'assets/06/examples/xml-nodelay.php', true);
xhr.send(null);
<p>WMD is taught by Davy De Winne & Bramus Van Damme</p>
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var html = xhr.responseText;
alert(html);
}
};
xhr.open('GET', 'assets/06/examples/html.php', true);
xhr.send(null);
eval()
it.
alert('<p>WMD is taught by Davy De Winne & Bramus Van Damme</p>');
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var js = xhr.responseText;
eval(js);
}
};
xhr.open('GET', 'assets/06/examples/js.php', true);
xhr.send(null);
eval()
though: eval()
is evil.
var head = document.getElementsByTagName("head")[0],
script = document.createElement('script');
script.type = 'text/javascript';
script.src = "/path/to/your/file.js";
head.appendChild(script);
{
"course": "WMD",
"lecturers": [
{
"id": 1,
"name": "Davy De Winne"
},
{
"id": 2,
"name": "Bramus Van Damme"
}
]
}
string
(double quotes required!)string
, number
, Object
, Array
, boolean
or null
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var json = JSON.parse(xhr.responseText), lecturers =[];
for (var i = 0, len = json.lecturers.length; i < len; i++) {
lecturers.push(json.lecturers[i].name);
}
alert('<p>' + json.course + ' is taught by ' + lecturers.join(' & ') + '</p>');
}
};
xhr.open('GET', 'assets/06/examples/json.php', true);
xhr.send(null);
JSON.parse()
(reverse: JSON.stringify()
)
JSON.parse()
require a library to do the parsing.Ajax: X is for JSON
Shut up and take my money!
$.ajax()
jQuery(document).ready(function($) {
$.ajax({
url: 'json.php',
type: 'get',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
var lecturers = [];
for (var i = 0, len = data.lecturers.length; i < len; i++) {
lecturers.push(data.lecturers[i].name);
}
$('#output').html('<p>' + data.course + ' is taught by ' + lecturers.join(' & ') + '</p>');
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
url
: A string containing the URL to which the request is sent.success
: A function to be called if the request succeeds.error
: A function to be called if the request fails.type
: Type of request to make (POST
or GET
). Defaults to GET
dataType
: Type of data you're expecting back from the server.
xml
html
script
— Will be interpreted automatically. Only via GET
.json
— Will be parsed automatically.jsonp
text
async
: Set to false
if you need synchronous requestsdata
: Extra data to be sent to the server (eg. form data)headers
: Extra headers to be sent along with the requestusername
& password
: HTTP Authenticationdata
parameter
key=value&key=value&key=value
var values = [
'firstname=' + encodeURIComponent($('#firstname').val()),
'lastname=' + encodeURIComponent($('#lastname').val())
];
var queryString = values.join('&');
$.fn.serialize()
var queryString = $('#signupform').serialize();
{key : "value"}
jQuery(document).ready(function($) {
$.ajax({
url: 'json.php',
type: 'get',
dataType: 'json'
}).success(function(data, textStatus, jqXHR) {
var lecturers = [];
for (var i = 0, len = data.lecturers.length; i < len; i++) {
lecturers.push(data.lecturers[i].name);
}
$('#output').html('<p>' + data.course + ' is taught by ' + lecturers.join(' & ') + '</p>');
}).error(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
});
succes
and error
functions in the call, you hook them onto the requestsuccess
and error
functions are bound to the promise$.when(deferred).then(function)
shorthand⚑jQuery(document).ready(function($) {
$.get('json.php', function(data, textStatus, jqXHR) {
var lecturers = [];
for (var i = 0, len = data.lecturers.length; i < len; i++) {
lecturers.push(data.lecturers[i].name);
}
$('#output').html('<p>' + data.course + ' is taught by ' + lecturers.join(' & ') + '</p>');
}, 'json');
});
jQuery(document).ready(function($) {
$.get('json.php', { key: "value" }, function(data, textStatus, jqXHR) {
// ...
}, 'json');
});
$.get()
jQuery(document).ready(function($) {
$.post('json.php', { key: "value" }, function(data, textStatus, jqXHR) {
// ...
}, 'json');
});
GET
jQuery(document).ready(function($) {
$('#output').load('html.php');
});
jQuery(document).ready(function($) {
$.getScript('js.php');
});
jQuery(document).ready(function($) {
$.getJSON('json.php', function(data, textStatus, jqXHR) {
var lecturers = [];
for (var i = 0, len = data.lecturers.length; i < len; i++) {
lecturers.push(data.lecturers[i].name);
}
$('#output').html('<p>' + data.course + ' is taught by ' + lecturers.join(' & ') + '</p>');
});
});
success
function of call #1 will invoke call #2success
function of call #2 will populate the pagefunction doAjax() { return $.get('foo.htm'); }
function doMoreAjax() { return $.get('bar.htm'); }
$.when(doAjax(), doMoreAjax())
.then(function(){
console.log('I am fired once BOTH ajax requests have completed!');
}).fail(function(){
console.log('I am fired if one or more requests failed');
});
$.ajax()
What's this? Hermes Conrad is closing the gap. He's limbo-ed out of retirement and straight into my heart!
<img src="spinner.gif" style="display: none;" id="spinner">
<div id="output"></div>
<script src="js/jquery-1.7.1.min.js"></script>
<script>
jQuery(document).ready(function($) {
$('#spinner').show();
$('#output').load('html-delay.php', function() {
$('#spinner').hide();
});
});
</script>
hash
of the window.location
hashchange
event to detect wheter a user has clicked the back/forward button and re-apply the statehash
and re-apply the statehistory.pushState()
and history.replaceState()
which allow you to manipulate the browser history
object
history.pushState()
= add new entry onto history object
history.replaceState()
= replace the current entry in history object
popstate
event
history.pushState()
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
stateObj
— An object you want to associate with the history entry. Will be returned when popstate
is triggeredtitle
— Title you wish to link to the history entry (ingored!)url
— URL to show in the address bar (optional)popstate
event
window.addEventListener('popstate', function(stateObj) {
console.log(stateObj); // { foo: "bar" }
});
history.pushState()
<ul>
<li><a href="#" id="link_1">link 1</a></li>
<li><a href="#" id="link_2">link 2</a></li>
<li><a href="#" id="link_3">link 3</a></li>
<li><a href="#" id="link_4">link 4</a></li>
</ul>
<script src="js/jquery-1.7.1.min.js"></script>
<script>
jQuery(document).ready(function($) {
$('ul').on('click', 'a', function(e) {
e.preventDefault();
$('ul a').css('background', 'inherit');
$(this).css('background', '#FF9');
});
});
</script>
Show demo →
history.pushState()
jQuery(document).ready(function($) {
$('ul').on('click', 'a', function(e) {
e.preventDefault();
$('ul a').css('background', 'inherit');
$(this).css('background', '#FF9');
history.pushState({'id':this.id}, 'clicked ' + this.id, '');
});
$(window).on('popstate', function(e) {
$('ul a').css('background', 'inherit');
if (e.originalEvent.state && e.originalEvent.state.id) {
$('#' + e.originalEvent.state.id).css('background', '#FF9');
}
});
});
Show demo →
http://site.com/proxy.php?route=ajax%2fuser%2flogin%3fparam_a%3d1%26param_b%3d2
proxy.php
fetches data from http://othersite.com/ajax/user/login?param_a=1¶m_b=2
proxy.php
outputs fetched dataproxy.php
Implementation
{"firstname" : "forrest", "lastname" : "gump"}
callbackFunction({"firstname" : "forrest", "lastname" : "gump"})
eval()
'd, thus the callback function — which will parse the JSONString to JSON — will be executedcallback
or jsonp
http://othersite.com/ajax/user/login?param_a=1&callback=callbackFunction
dataType
to being jsonp
$.ajax({
url: 'jsonp.php',
type: 'get',
dataType: 'jsonp',
success: function(data, textStatus, jqXHR) {
// ...
}
});
GET
eval()
'dXMLHttpRequest2
header('Access-Control-Allow-Origin: othersite.com');
*
to allow calls from any domainGET
http://othersite.com/ajax/user/login?param_a=1&apikey=yourapikey
$.ajax({
url: 'json.php',
dataType: 'json',
header : { 'X-Api-Key' : 'yourapikey' },
success: function(data, textStatus, jqXHR) {
// ...
}
});