13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

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

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

874 Chapter 34 Building <strong>Web</strong> 2.0 Applications with Ajax<br />

The value of params is then sent to the back-end <strong>PHP</strong> script in the last line of the function:<br />

myReq.send(params);<br />

Before the values are sent, three request headers are also sent so that the server knows<br />

how to h<strong>and</strong>le the data sent in the POST request:<br />

myReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");<br />

myReq.setRequestHeader("Content-length", params.length);<br />

myReq.setRequestHeader("Connection", "close");<br />

The next step in this process is to create the JavaScript function to h<strong>and</strong>le the server<br />

response; we have called this addBMResponse:<br />

myReq.onreadystatechange = addBMResponse;<br />

Again, this code is similar to the theHTTPResponse function created earlier in the chapter.The<br />

code for addBMResponse is seen in Listing 34.7.<br />

Listing 34.7<br />

The JavaScript Function addBMResponse()<br />

function addBMResponse() {<br />

if (myReq.readyState == 4) {<br />

if(myReq.status == 200) {<br />

result = myReq.responseText;<br />

document.getElementById('displayresult').innerHTML = result;<br />

} else {<br />

alert('There was a problem with the request.');<br />

}<br />

}<br />

}<br />

This JavaScript function first checks the state of the object; if it has completed its<br />

process, it next checks that the response code from the server was 200 (OK). If the<br />

response code is not 200, an alert is shown with the words “There was a problem with<br />

the request.” Any other responses will come from the execution of the add_bms.php<br />

script <strong>and</strong> will be displayed in a div with an id value of displayresult. For the<br />

moment, the displayresult id is defined in the new_ss.css style sheet as follows (a<br />

white background):<br />

#displayresult {<br />

background: #fff;<br />

}

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

Saved successfully!

Ooh no, something went wrong!