25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Download from Wow! eBook <br />

132<br />

CHAPTER 5 ■ USING THE COMMUNICATION APIS<br />

if (typeof xhr.withCredentials === undefined) {<br />

document.getElementById("support").inner<strong>HTML</strong> =<br />

"Your browser doesnot support cross-origin XMLHttpRequest";<br />

} else {<br />

document.getElementById("support").inner<strong>HTML</strong> =<br />

"Your browser does support cross-origin XMLHttpRequest";<br />

}<br />

Next, set callback functions to handle the progress events and calculate the uploaded and<br />

downloaded ratios.<br />

xhr.upload.onprogress = function(e) {<br />

var ratio = e.loaded / e.total;<br />

set<strong>Pro</strong>gress(ratio + "% uploaded");<br />

}<br />

xhr.onprogress = function(e) {<br />

var ratio = e.loaded / e.total;<br />

set<strong>Pro</strong>gress(ratio + "% downloaded");<br />

}<br />

xhr.onload = function(e) {<br />

set<strong>Pro</strong>gress("finished");<br />

}<br />

xhr.onerror = function(e) {<br />

set<strong>Pro</strong>gress("error");<br />

}<br />

Finally, open the request and send the string containing the encoded geolocation data. This will be a<br />

cross-origin request because the target location is a URL with a different origin than the page.<br />

var targetLocation = "http://geodata.example.net:9999/upload";<br />

xhr.open("POST", targetLocation, true);<br />

geoDataString = dataElement.textContent;<br />

xhr.send(geoDataString);<br />

The Final Code<br />

Listing 5-9 shows the complete application code—the contents of the crossOriginUpload.html file.<br />

Listing 5-9. Contents of crossOriginUpload.html<br />

<br />

Upload Geolocation Data<br />

<br />

<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!