About the Plug-in This plug-in takes the URL of a web page, any parameters to pass to it and a Document Object Model DOM target for inserting the result.. It doesn’t return any parameter
Trang 1About the Plug-in This plug-in takes the URL of a web page, any parameters to pass to it and a Document Object Model (DOM) target for inserting the result It doesn’t return any parameters, but upon success the contents of target are populated with the result returned from the web server Upon failure, an alert box will appear to aid with debugging You may wish to disable this behavior on a production web site It requires the following arguments:
• url A web page/program to call
• params Any POST parameters to pass, separated by & characters, like this:
var1=val1&var2=val2
• target A DOM element in which to place the result of the call
Variables, Arrays, and Functions
request XMLHttpRequest object, or the value false on failure
How It Works This is the second plug-in that is entirely written in JavaScript It first calls PIPHP_JS_
AjaxRequest() to create a new XMLHttpRequest object in request Next the onreadystatechange event of request is assigned to an inline anonymous function
When this state changes, which means a step in the Ajax process has completed, the function is called There is only one state of interest to this function and that’s the value 4, which indicates a completed Ajax call This value is in this.readyState
F IGURE 11-2 A one-line PHP program interfaces with a browser via Ajax to insert a web page into an HTML
element.
Trang 2In JavaScript the keyword this applies to the current object being processed Here it could equally be replaced with the word request to directly access the object Next the function only wants to know if the call completed successfully, which is indicated by this status having a value of 200
With both of those cases being true this.responseText is tested to ensure a value of null hasn’t been returned, and if not, the innerHTML contents of the target argument is assigned the value returned by the Ajax call in this.responseText
So, if target is being used to assign the Ajax result to, for example, a <div> with the id 'info', then target will have been give the value:
document.getElementById('info')
This means that the statement:
target.innerHTML = this.responseText
is equivalent to:
document.getElementById('info').innerHTML = this.responseText
Therefore the text within the two following <div> tags would be replaced with the new text from the Ajax call:
<div id='info'>The contents of this DIV will be replaced</div>
If the value of this.responseText is null, an alert message appears, as also happens
if this.status doesn’t have the value 200 These alert commands are useful while you are debugging code but you may want to remove them when using this plug-in on a production server
After assigning the function to request.onreadystatechange, request.open() is called and passed three parameters: "POST", for a POST request; the URL to access in url; and the value true, indicating that the request should take place asynchronously
Next, three headers have to be sent to the server These are to tell the server to expect URL encoded form data, to pass the length of the data the server should expect to receive, and to then close the header connection
Finally, the Ajax request is initiated using a call to request.send() with an argument
of params
How to Use It The following example shows how you would use this function To help you see what is
going on I have included both the Ajax Request and the Post Ajax Request plug-ins within the
example, which is totally complete except for the PHP component (which comes afterwards):
<html><head><title>AJAX POST Example</title>
</head><body><center />
<h1>Loading a page in DIV tags</h1>
<div id='info'>The contents of this DIV will be replaced</div>
<script type="text/javascript">
Trang 3PIPHP_JS_PostAjaxRequest('ajaxpost.php', 'url=http://m.facebook.com/',
document.getElementById('info'))
function PIPHP_JS_PostAjaxRequest(url, params, target) {
request = new PIPHP_JS_AjaxRequest()
request.onreadystatechange = function() {
if (this.readyState == 4)
if (this.status == 200)
if (this.responseText != null) target.innerHTML = this.responseText // You can remove these two alerts after debugging else alert("Ajax error: No data received") else alert( "Ajax error: " + this.statusText) }
request.open("POST", url, true) request.setRequestHeader("Content-type", "application/x-www-form-urlencoded") request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close") request.send(params)
}
function PIPHP_JS_AjaxRequest() {
try { var request = new XMLHttpRequest() }
catch(e1) {
try { request = new ActiveXObject("Msxml2.XMLHTTP") }
catch(e2) {
try { request = new ActiveXObject("Microsoft.XMLHTTP") }
catch(e3) {
request = false }
} } return request }
</script>
Trang 4Note that the entire Facebook page is being loaded into the <div>, in the same way as if you had included it within an <iframe> element This is purely an example of how to incorporate such a page, and you do not gain access to the Facebook API using this method Instead a surfer using such an embedded page to log in will be directed straight to the Facebook servers for the remainder of the process
To try this example for yourself, type it in and save it as ajaxpost.html You can also download it from the Download link at www.pluginphp.com After extracting the file plug-ins.
zip , you will find the example in the location 11/ajaxpost.html.
However, don’t run the file until you also have the PHP part of the equation on the server It’s not a large program but it’s very important because it’s the part of the process that receives requests from the browser and responds to them In this case, it returns a requested web page:
<?php // ajaxpost.php
if (isset($_POST['url'])) echo file_get_contents($_POST['url']);
?>
What this program does is check whether the variable url has been posted to it, and if so,
it loads the page pointed to by the value of url into memory using the function file_get_ contents() It then uses the echo command to return the URL to the calling program—in
this case, the Ajax call made by the browser This file should be typed in and saved as ajaxpost
.php , or you can find it in the same folder as the ajaxpost.html program if you download it from
the companion web site
Of course, your PHP programs are likely to be far more complex than this one, and may return all manner of items to the browser, such as information on available usernames when signing up to a site, or new messages on a social networking site, and so on
The Plug-in
function PIPHP_JS_PostAjaxRequest(url, params, target) {
request = new PIPHP_JS_AjaxRequest()
request.onreadystatechange = function() {
if (this.readyState == 4)
if (this.status == 200)
if (this.responseText != null) target.innerHTML = this.responseText // You can remove these two alerts after debugging else alert("Ajax error: No data received") else alert( "Ajax error: " + this.statusText) }
request.open("POST", url, true) request.setRequestHeader("Content-type", "application/x-www-form-urlencoded") request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close") request.send(params)
}
Trang 5Get Ajax Request GET requests are also supported via Ajax and they can achieve the same results as POST requests The only main difference is that the data sent back to the server is passed in the tail of a URL, known as the query string, rather than in HTML headers Figure 11-3 shows the Amazon mobile home page being loaded into a <div> … </div> pair of tags using this plug-in
About the Plug-in This plug-in takes the URL of a web page, any parameters to pass to it, and a Document Object Model (DOM) target for inserting the result It doesn’t return any parameters, but upon success, the contents of target are populated with the result returned from the web server Upon failure, an alert box will appear to aid with debugging You may wish to disable this behavior on a production web site It requires the following arguments:
• url A web page or program to call
• params Any GET parameters to pass, separated by & characters, like this:
var1=val1&var2=val2
• target A DOM element in which to place the result of the call
Variables, Arrays, and Functions
nocache String randomly assigned a value to overcome caching request XMLHttpRequest object, or the value false on failure
F IGURE 11-3 Ajax works equally well with either POST or (as shown here) GET requests.
83