Passing Data to Server-Side Scripts


So data.php works. Still, the text it returns is static. How could it be otherwise, since you’re not passing any data to data.php to customize what it returns? But you can pass data to the server, and the way you do that differs if you’re using the GET or POST method.

Using GET is easiest, so that’s coming up first.

Passing data to the server with GET

Say that you wanted to have two messages returned from the server, depending on data you pass to the server. For example, if you passed a value of 1 to the server, you’d get back 'You sent the server a value of 1', and if you pass a value of 2 to the server, you’d get back 'You sent the server a value of 2' instead.

Arranging this in PHP is easy. When you send data to the server, you assign that data to a parameter. In this case, you might just call that parameter "data" to make life easier. You might call the PHP script datahandler.php in this case, and because you’re passing data using the GET HTTP method, you can recover the data you’re sending in PHP code using a special PHP array named $_GET. For example, if you assign the parameter data a value of 1 and send that to the datahan-dler.php script, then the body of this if statement executes:

 <?   if ($_GET["data"] == "1") {     .     .     .   } ?>

In this case, you can send the message 'You sent the server a value of 1' back to the browser like this:

 <?   if ($_GET["data"] == "1") {     echo 'You sent the server a value of 1';   } ?>

On the other hand, if you assign the data parameter the value 2, you can send back the message 'You sent the server a value of 2' like this:

 <?   if ($_GET["data"] == "1") {     echo 'You sent the server a value of 1';   }   if ($_GET["data"] == "2") {     echo 'You sent the server a value of 2';   } ?>

That handles the situation in PHP code: when you pass it a parameter named data that’s been assigned the value of 1, you get back the first message; when you pass it a value of 2 assigned to the data parameter, you get back the second message.

Now how do you pass data to the server when you’re using the GET method and Ajax? When you use the GET method of fetching data from the server, data is sent from Web pages back to the server using URL encoding, which means that data is appended to the actual URL that is sent to the server.

For example, if you were using the GET method and you had a standard Web page with a text field named "a" that contained the number 5, a text field named "b" that contained the number 6, and a text field named "c" that contained the text "Now is the time", all that data would be encoded and added to the URL you’re accessing. The names of the text fields a, b, and c, are the parameters you’re sending to the server, and the text in each text field is the data assigned to each parameter.

When data is URL encoded, a question mark (?) is added to the end of the URL, and the data, in name=data format, is added after that question mark. Spaces in text are converted to a plus sign (+), and you separate pairs of name=data items with ampersands (&). So to encode the data from the "a", "b", and "c" text fields and send it to http://www.servername.com/user/scriptname, you’d use this URL:

  • http://www.servername.com/user/scriptname?a=5&b=6&c=Now+is+the+time

Note 

The data you send this way is always text; even if you’re sending numbers, they’re treated as text.

So that’s the way you send data from controls like text fields: by treating the names given to the text fields as parameters and assigning data to those parameters. You don’t have any text fields here, however, so this example, datahandler.html, just assigns a value of 1 or 2 to the data parameter so the PHP script can get and read that data. For example, this URL assigns a value of 1 to a parameter named data and sends it to the datahandler.php script:

 datahandler.php?data=1

Here’s how to display two buttons in the datahandler.html application that let the user display the first and second messages:

 <html>   <head>     <title>An Ajax demo</title>     <script language = "javascript">       var XMLHttpRequestObject = false;       if (window.XMLHttpRequest) {         XMLHttpRequestObject = new XMLHttpRequest();       } else if (window.ActiveXObject) {         XMLHttpRequestObject = new           ActiveXObject("Microsoft.XMLHTTP");       }       function getData(dataSource, divID)       {         if(XMLHttpRequestObject) {           var obj = document.getElementById(divID);           XMLHttpRequestObject.open("GET", dataSource);           XMLHttpRequestObject.onreadystatechange = function()           {              if (XMLHttpRequestObject.readyState == 4 &&                XMLHttpRequestObject.status == 200) {                  obj.innerHTML =                    XMLHttpRequestObject.responseText;              }            }            XMLHttpRequestObject.send(null);         }       }     </script>   </head>   <body>     <H1>An Ajax demo</H1>     <form>       <input type = "button" value = "Fetch message 1"         onclick = "getData('datahandler.php?data=1',           'targetDiv')">       <input type = "button" value = "Fetch message 2"         onclick = "getData('datahandler.php?data=2',           'targetDiv')">     </form>     <div >       <p>The fetched message will appear here.</p>     </div>   </body> </html>

You can see this Web page, index3.html, in Figure 3.5.

image from book
Figure 3.5: Interacting with the server by passing data

When the user clicks a button, the corresponding message is downloaded and displayed, as you see in Figure 3.6. You’ve now passed data to a server-side script using Ajax and the GET method.

When you use the GET method, things work out fine, but there’s one thing to consider: your data is very public. That’s because it was attached to the end of the URL you’re accessing, which means it could, possibly, be read by others easily. A somewhat more secure method is the POST method, which encodes your data in HTTP headers.

image from book
Figure 3.6: Retrieving a message from the server

Passing data to the server with POST

Using the POST HTTP method means that any data you send to the server is enclosed in the HTTP request header, so it’s not as visible (which doesn’t mean it’s secure) as with the GET method. In fact, POST is coming to be preferred over GET for that very reason.

When you use the POST method and Ajax, you have to work things a little differently in the code, as you’re going to see. And the PHP is different as well; instead of using the $_GET array:

 <?   if ($_GET["data"] == "1") {     echo 'You sent the server a value of 1';   }   if ($_GET["data"] == "2") {     echo 'You sent the server a value of 2';   } ?>

you use the $_POST array, like this in datahandlerpost.php:

 <?   if ($_POST["data"] == "1") {     echo 'You sent the server a value of 1';   }   if ($_POST["data"] == "2") {     echo 'You sent the server a value of 2';   } ?> 

Now you have to modify your Ajax application to use POST instead of GET. The first step is obvious: you change this line, where you use the GET method:

 function getData(dataSource, divID) {   if(XMLHttpRequestObject) {     var obj = document.getElementById(divID);     XMLHttpRequestObject.open("GET", dataSource);     .     .     .

to this, where you use the POST method:

 function getData(dataSource, divID) {   if(XMLHttpRequestObject) {     var obj = document.getElementById(divID);     XMLHttpRequestObject.open("POST", dataSource);     .     .     .

In order to use the POST method and send data to the server, you also have to set an HTTP request header, the Content-Type request header, to "application/x-www-form-urlencoded". If you don’t know what that means, just make sure you include this code:

 function getData(dataSource, divID) {   if(XMLHttpRequestObject) {     var obj = document.getElementById(divID);     XMLHttpRequestObject.open("POST", dataSource);     XMLHttpRequestObject.setRequestHeader('Content-Type',       'application/x-www-form-urlencoded');     .     .     .

Next comes the standard anonymous function to handle the download, and that look like this in datahandlerpost.html:

 function getData(dataSource, divID) {   if(XMLHttpRequestObject) {     var obj = document.getElementById(divID);     XMLHttpRequestObject.open("POST", dataSource);     XMLHttpRequestObject.setRequestHeader('Content-Type',       'application/x-www-form-urlencoded');     XMLHttpRequestObject.onreadystatechange = function()     {       if (XMLHttpRequestObject.readyState == 4 &&         XMLHttpRequestObject.status == 200) {           obj.innerHTML =             XMLHttpRequestObject.responseText;       }     }     .     .     .

So far, so good, but if you can’t URL-encode the data you send using the POST method, how do you actually assign the data parameter a value of 1 or 2, depending on which button the user clicks, and send that data to the server?

You might start by changing each button so that it calls the getData function with the number of the message to get, 1 or 2:

     function getData(dataSource, divID)     {       if(XMLHttpRequestObject) {         var obj = document.getElementById(divID);         XMLHttpRequestObject.open("POST", dataSource);         XMLHttpRequestObject.setRequestHeader('Content-Type',           'application/x-www-form-urlencoded');         XMLHttpRequestObject.onreadystatechange = function()         {           if (XMLHttpRequestObject.readyState == 4 &&             XMLHttpRequestObject.status == 200) {                obj.innerHTML =                  XMLHttpRequestObject.responseText;           }         }         .         .         .       }     }   </script> </head> <body>   <H1>An Ajax demo</H1>   <form>     <input type = "button" value = "Fetch message 1"       onclick = "getData('datahandlerpost.php', 'targetDiv',         1)">     <input type = "button" value = "Fetch message 2"       onclick = "getData('datahandlerpost.php', 'targetDiv',         2)">   </form>         .         .         .

Then you modify the getData function to accept a third parameter, the data parameter, which will be set to 1 or 2, depending on which button was clicked, and therefore which message the user wants to see:

 function getData(dataSource, divID, data) {   if(XMLHttpRequestObject) {     var obj = document.getElementById(divID);     XMLHttpRequestObject.open("POST", dataSource);     XMLHttpRequestObject.setRequestHeader('Content-Type',       'application/x-www-form-urlencoded');     XMLHttpRequestObject.onreadystatechange = function()     {       if (XMLHttpRequestObject.readyState == 4 &&          XMLHttpRequestObject.status == 200) {            obj.innerHTML =              XMLHttpRequestObject.responseText;       }     }     .     .     .   } }

Here comes the central point: instead of sending a value of null with the send XMLHttpRequest object, as you did when using the GET method, you send the actual data to the server using the send method when you use POST. And you send that data just as you would a URL-encoded string. For example, to send the data assigned to a parameter named data, you do this:

 function getData(dataSource, divID, data) {   if(XMLHttpRequestObject) {     var obj = document.getElementById(divID);     XMLHttpRequestObject.open("POST", dataSource);     XMLHttpRequestObject.setRequestHeader('Content-Type',       'application/x-www-form-urlencoded');     XMLHttpRequestObject.onreadystatechange = function()     {       if (XMLHttpRequestObject.readyState == 4 &&         XMLHttpRequestObject.status == 200) {           obj.innerHTML =             XMLHttpRequestObject.responseText;       }     }     XMLHttpRequestObject.send("data=" + data);   } }

And that’s it. You’re now using POST instead of GET to send data to the server. You can see this Web page, datahandlerpost.html, in Figure 3.7.

image from book
Figure 3.7: Interacting with the server by passing data using POST

Just as with the GET method, when the user clicks a button, the corresponding message is downloaded and displayed, as you see in Figure 3.8.

image from book
Figure 3.8: Retrieving a message from the server using POST

You’ve gotten a good number of Ajax basics down, but there’s still a glaring hole: what about XML? After all, Ajax means Asynchronous JavaScript and XML, doesn’t it? XML is coming up next.



Ajax Bible
Ajax Bible
ISBN: 0470102632
EAN: 2147483647
Year: 2004
Pages: 169

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net