27.10.2015 Views

AJAX and PHP

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10<br />

}<br />

}<br />

}<br />

else if (action =="delTask")<br />

params = "?content=" + content + "&action=delTask";<br />

// don't add null params to cache<br />

if (params) cache.push(params);<br />

// try to connect to the server<br />

try<br />

{<br />

// only continue if the connection is clear <strong>and</strong> cache is not empty<br />

if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0)<br />

&& cache.length>0)<br />

{<br />

// get next set of values from cache<br />

var cacheEntry = cache.shift();<br />

// initiate the request<br />

xmlHttp.open("GET", "drag-<strong>and</strong>-drop.php" + cacheEntry, true);<br />

xmlHttp.setRequestHeader("Content-Type",<br />

"application/x-www-form-urlencoded");<br />

xmlHttp.onreadystatechange = h<strong>and</strong>leRequestStateChange;<br />

xmlHttp.send(null);<br />

}<br />

else<br />

{<br />

setTimeout("process();", 1000);<br />

}<br />

}<br />

// display the error in case of failure<br />

catch (e)<br />

{<br />

displayError(e.toString());<br />

}<br />

// function that retrieves the HTTP response<br />

function h<strong>and</strong>leRequestStateChange()<br />

{<br />

// when readyState is 4, we also read the server response<br />

if (xmlHttp.readyState == 4)<br />

{<br />

// continue only if HTTP status is "OK"<br />

if (xmlHttp.status == 200)<br />

{<br />

try<br />

{<br />

postUpdateProcess();<br />

}<br />

catch(e)<br />

{<br />

// display error message<br />

displayError(e.toString());<br />

}<br />

}<br />

else<br />

{<br />

displayError(xmlHttp.statusText);<br />

}<br />

}<br />

}<br />

// Processes server's response<br />

function postUpdateProcess()<br />

{<br />

// read the response<br />

var response = xmlHttp.responseText;<br />

// server error?<br />

247<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!